文件/目录路径应如下所示 - Powershell输出

时间:2014-08-04 08:36:59

标签: windows powershell output powershell-v2.0 powershell-v3.0

我正在使用Powershell脚本,它应该创建一个包含目录顺序(文件夹,子文件夹,文件等)的文件:

$path = "golf.de/dgv" 
Get-ChildItem -Path $folder -recurse | sort Directory, Name| format-Table -auto $path, Directory, Name | Out-File C:\Users\J.Kammermeier\Desktop\Johannes\testtext.txt

直到现在输出看起来像这样

C:\Users\J.Kammermeier\Desktop\Johannes                        Test-Datei1.txt         
C:\Users\J.Kammermeier\Desktop\Johannes                        Test-Datei2.txt
C:\Users\J.Kammermeier\Desktop\Johannes\Sonstige Datein\Musik  WACKEN.txt 

但我按此顺序需要它:

.../Johannes                         Test-Datei1.txt 

...Johannes\Sonstige Datein\Musik    WACKEN.txt 

如何实现它?

1 个答案:

答案 0 :(得分:5)

您必须使用Directorycalculated properties稍微破坏Select-Object属性:

# Set the path and folder property
$path = "golf.de/dgv"
$folder = "C:\Users\J.Kammermeier\Desktop\Johannes"

# Get the name of the parent folder (the part we want to remove)
$basePath = (Get-Item $folder).Parent.FullName

# Retrieve the files
$files = Get-ChildItem -Path $folder -Recurse 

# Select the Name property and then two calculated properties, "Directory" and "Path"
$files = $files |Select-Object @{Name="BaseURL";Expression={"$path"}},
                               @{Name="Directory";Expression={$_.Directory.FullName.Substring($basePath.Length - 1)}},
                               Name

# Sort them
$files = $files |Sort-Object Directory, Name
# Formatted output to file
$files | Format-Table -AutoSize | Out-File C:\Users\J.Kammermeier\Desktop\Johannes\testtext.txt

根据详细信息,我猜您正在尝试审核网站的文件,您可以合并PathDirectory属性并使用-replace修复反斜杠:

@{Name="URLPath";Expression={"$path/" + $($_.Directory.FullName.Substring($basePath.Length - 1) -replace "\\","/")}}