PowerShell - 将父文件夹名称添加到文件名

问题描述

我有这个文件夹结构

android.useandroidX=true 
android.enableJetifier=true

我想将文本文件重命名root\1\2\3\1.txt root\3\2\4\6\1.txt 我试过了

root_1.txt

但这不起作用,因为父级仅适用于目录

解决方法

对于文件项,使用 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