我建议你输出objects https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-pscustomobject?view=powershell-7.2在任何情况下,您都可以使用以下方式获取相对路径,而不是像您现在所做的那样.SubString(..) https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=net-6.0:
foreach ($f in Get-ChildItem -Path $srcpth -File -Recurse) {
[pscustomobject]@{
FileName = $f.Name
FileSize = $f.Length
RelativePath = $f.FullName.Substring($srcpth.Length + 1)
}
}
或者如果你正在使用PowerShell核心,您可以访问.NET APIPath.GetRelativePath(String, String) https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getrelativepath?view=net-6.0#system-io-path-getrelativepath(system-string-system-string):
foreach ($f in Get-ChildItem -Path $srcpth -File -Recurse) {
[pscustomobject]@{
FileName = $f.Name
FileSize = $f.Length
RelativePath = [IO.Path]::GetRelativePath($srcpth, $f.FullName)
}
}
还有PathIntrinsics.NormalizeRelativePath(String, String) Method https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.pathintrinsics.normalizerelativepath?view=powershellsdk-7.0.0Windows PowerShell 和 PowerShell Core 都可用,尽管这似乎有点矫枉过正:
$ExecutionContext.SessionState.Path.NormalizeRelativePath($f.FullName, $srcpth)