将父文件夹名称添加到文件名中?

问题描述 投票:0回答:2

我有这个文件夹结构

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 仅适用于目录

powershell scripting rename parent-child
2个回答
3
投票

对于文件项,请使用

Directory
属性:

Get-ChildItem -Recurse *.txt | Rename-Item -NewName {$_.Directory.Parent.Name + $_.Name}

0
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.