[英]How Get-Childitem and only include subfolders and files?
我有一個腳本,目前我執行以下操作,它獲取子目錄中文件的完整路徑:
$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"
但是,為了讓我生成的網頁在我們的外聯網上工作,我無法提供文件的完整路徑。 我只需要它返回:
"Initial Forms/General Forms/Background Check.pdf"
這將是我可以在外聯網上使用的鏈接。 如何讓 get-childitem 只返回子路徑?
我的腳本是從
//server/group/Creds/Documents
我找不到任何類似的例子。 我也想避免對腳本位置進行硬編碼,以防它被移動。
簡單的方法是簡單地修剪不需要的路徑,包括尾部斜杠:
$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 + "\","")}
我建議以下方法:
$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)
}
.GetRelativePath()
:在 PowerShell Core 中,底層 .NET Core 框架的System.IO.Path
類型現在有一個.GetRelativePath()
方法,這是一種通過引用路徑從絕對路徑獲取相對路徑的便捷方法:
# PowerShell *Core* only.
PS> [IO.Path]::GetRelativePath('/foo/bar', '/foo/bar/bam/baz.txt')
bam/baz.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.