The following assumes that your CSV file contains the file names with extension - adjust as needed.
Build a hashtable from the CSV whose entries are keyed by Column A
values and each contain the corresponding Column B
value.
Filter the Get-ChildItem
output with Where-Object
to only process files whose name is present as a key in the hashtable.
- Note that switch
-File
is added to the Get-ChildItem
call below, so as to process files only (not also directory objects).
Rename each matching file to the value of the relevant hashtable entry.
# Build a hashtable from the CSV that with old-name-new-name pairs.
$ht = [ordered] @{} # Note: you can omit [ordered] in this case.
Import-Csv file.csv |
ForEach-Object { $ht[$_.'Column A'] = $_.'Column B' }
Get-ChildItem -Path C:\ -File -Recurse -ErrorAction SilentlyContinue |
Where-Object { $ht.Contains($_.Name) } |
Rename-Item -NewName { $ht[$_.Name] } -WhatIf
Note: The -WhatIf
common parameter in the command above previews the operation. Remove -WhatIf
once you're sure the operation will do what you want.
Note: As an alternative to filtering Get-ChildItem
output with Where-Object
after the fact, you could use the former's -Include
parameter as follows:
-Include $ht.Keys
- However, up to at least PowerShell 7.2.x,
-Include
is actually slower than a post-filtering solution - see this answer.