【问题标题】:How Get-Childitem and only include subfolders and files?如何Get-Childitem 只包含子文件夹和文件?
【发布时间】:2019-08-27 13:34:24
【问题描述】:

我有一个脚本,目前我执行以下操作,获取子目录中文件的完整路径:

$filenameOut = "out.html"

#get current working dir
$cwd = Get-ScriptDirectory 

#get files to display in lists
$temp = Join-Path $cwd "Initial Forms"
$temp = Join-Path $temp "General Forms"
$InitialAppointmentGenArr = Get-ChildItem -Path $temp 

所以这将返回一个列表,其中数组中的第一个文件如下所示:

"//server/group/Creds/Documents/Initial Forms/General Forms/Background Check.pdf"

但是,要让我生成的网页在我们的 Extranet 上运行,我无法提供文件的完整路径。我只需要它返回:

"Initial Forms/General Forms/Background Check.pdf"

这将是我可以在外联网上使用的链接。如何让 get-childitem 只返回子路径?

我的脚本是从

运行的
//server/group/Creds/Documents

我找不到任何类似的例子。我也想避免对脚本位置进行硬编码,以防它被移动。

【问题讨论】:

  • 你不能那样做。 [grin] 但是,您可以将完整路径的 $CWD 部分替换为空。

标签: powershell file get-childitem subdirectory


【解决方案1】:

简单的方法是简单地修剪不需要的路径,包括尾部斜杠:

$filenameOut = "out.html"

#get current working dir
$cwd = Get-ScriptDirectory 

#get files to display in lists
$temp = Join-Path $cwd "Initial Forms"
$temp = Join-Path $temp "General Forms"

$FullPath = Get-ChildItem -Path $temp 
$InitialAppointmentGenArr = $FullPath | %{ $_.FullName.Replace($cwd + "\","")}

【讨论】:

  • 谢谢!好主意!我不得不用 cwd 做到这一点: $filePath = $file.FullName.Replace($cwd+"\","")
  • 用正确的路径斜杠更新了答案。
【解决方案2】:

我建议以下方法:

$relativeDirPath = Join-Path 'Initial Forms' 'General Forms'

Get-ChildItem -LiteralPath $PSScriptRoot/$relativeDirPath | ForEach-Object {
  Join-Path $relativeDirPath $_.Name
}

请注意,我使用$PSScriptRoot 代替了$cwd,因为听起来后者包含您的脚本所在的目录,而自动变量$PSScriptRoot 直接报告。

这是一个通用的变体,它也适用于递归使用Get-ChildItem

$relativeDirPath = Join-Path 'Initial Forms' 'General Forms'

Get-ChildItem -LiteralPath $PSScriptRoot/$relativeDirPath | ForEach-Object {
  $_.FullName.Substring($PSScriptRoot.Length + 1)
}

顺便说一句:在跨平台的 PowerShell (Core) 7+ 版本中,底层 .NET Core 框架的 System.IO.Path 类型现在有一个 .GetRelativePath() method,这是从绝对路径获取相对路径的便捷方式一、通过引用路径:

# PowerShell (Core) 7+ only.
PS> [IO.Path]::GetRelativePath('/foo/bar', '/foo/bar/bam/baz.txt')
bam/baz.txt

注意:

  • 由于 .NET 的工作目录通常与 PowerShell 的不同,因此请务必提供完整输入路径。

  • 另外,请确保路径是文件系统原生路径,而不是基于 PowerShell-only 驱动器。

  • Convert-Path 可用于确定完整的文件系统原生路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 2020-09-08
    • 2019-08-26
    • 2015-09-14
    • 1970-01-01
    相关资源
    最近更新 更多