这里是我的目录和文件
C:folder1filename1.pdf
C:folder2filename2.pdf
我想输出如下格式
<root><folder>folder1</folder><file>filename</file></root>
<root><folder>folder2</folder><file>filename</file></root>
我可以用下面的命令输出完整的路径。
Get-ChildItem -Path C:** -Recurse |
Foreach-Object {$_.FULLName}{ Convert-Path $_.PSPath }{ ($_.PSPath -split '[\]')[-1] }
输出
C:folder1filename1.pdf
C:folder2filename2.pdf
如何在PowerShell中实现这一点?
如果您想要这样的输出(类似于XML),您可以使用返回的FileInfo对象具有的属性并使用-f
格式操作符格式化您喜欢的属性:
Get-ChildItem -Path 'C:**' -File -Recurse | ForEach-Object {
# $_.Directory.Name gives you the directory name of the parent folder
# $_.DirectoryName gives the full path to the folder where the file is
# if you don't want the extension, use $_.BaseName instead of $_.Name
'<root><folder>{0}</folder><file>{1}</file></root>' -f $_.Directory.Name, $_.Name
# if you want the whole folder path without the root (C:), then use
# $root = [System.IO.Path]::GetPathRoot($_.FullName)
# $folder = $_.DirectoryName.Substring($root.Length)
# '<root><folder>{0}</folder><file>{1}</file></root>' -f $folder, $_.Name
}