我有这个文件夹结构
root\1\2\3\1.txt
root\3\2\4\6\1.txt
我想将文本文件重命名为
root_1.txt
我试过了
Get-ChildItem -Recurse *.txt | Rename-Item -NewName %{$_.Parent.Parent.Name + $_.Name}
但这不起作用,因为 Parent 仅适用于目录
对于文件项,请使用
Directory
属性:
Get-ChildItem -Recurse *.txt | Rename-Item -NewName {$_.Directory.Parent.Name + $_.Name}
Get-ChildItem -Recurse *.txt |
Where-Object { ($_.FullName | Split-Path -NoQualifier ) -match '^\\(.+?)\\' } | # Get root folder using -match and regex
Rename-Item -NewName { $Matches[1] + '_' + $_.Name } -WhatIf # Build new name from $Matches[1] and filename
# Remove -WhatIf after testing