我有以下哈希表。
$m = @{
"AAA" = "XX";
"BBB" = "YY";
"CCC" = "ZZ";
....
}
我想将名称以“AAA”开头的文件重命名为“XX ....”,“BBB”重命名为“YY ....”等。 例如,“AAA1234.txt”将重命名为“XX1234.txt”。
如何在Powershell中执行此操作?
答案 0 :(得分:2)
此代码适用于我:
$m = @{"AAA" = "XX"; "BBB" = "YY"}
$files = gci *.txt
$m.GetEnumerator() | % {
$entry = $_ # save hash table entry for later use
$files | ? { $_.Name.StartsWith($entry.Key) } |
% {
$trimmed = $_.Name.Substring($entry.Key.length) # chops only the first occurence
$newName = $entry.Value + $trimmed
$_ | Rename-Item -NewName $newName
}
}