我试图读取文件目录,然后在CSV文件中搜索文件,该文件具有两列名称:newname。我想查找文件,然后使用newname重命名原始文件。有时,我的原始文件会从CSV列表中丢失。
$folder = "c:\test\"
$csv = "C:\tests\replace.csv"
$keywords = @{}
Import-Csv $csv | ForEach-Object {
$keywords[$_.Search] = $_.Replace
}
Get-ChildItem $folder -Recurse | ForEach-Object {
$newname = $_.Name
foreach ($word in $keywords.Keys) {
$newname = $newname.Replace($word, $keywords[$word])
}
if ($_.Name -ne $newname) {
Rename-Item -Path $_.FullName -NewName $newname
}
}
它确实对某些文件有效,然后根据newname字段将一个文件重命名为一个长字符串。任何帮助都会很棒。
答案 0 :(得分:0)
LotPings已经说过:由于您已经创建了 lookup-hashtable ,因此无需为每个项目都进行迭代-只需像这样传递文件名作为密钥即可:
# replace this with your Import-Csv later
$csv_data = "Search,Replace
old_file.txt,new_file.txt
old_file2.csv,new_file2.csv
"
$folder = ".\testfiles"
$keywords = @{ }
$replace_data = $csv_data | ConvertFrom-Csv # replace this with your Import-Csv later
$replace_data | ForEach-Object {
$keywords[$_.Search] = $_.Replace
}
Get-ChildItem $folder -Recurse | ForEach-Object {
$file_name = $_.Name
# skip files that are not listed in your csv
if ($keywords."$file_name") {
Rename-Item $_.FullName $keywords."$file_name"
}
}