I've got a lot of folders that I want to batch rename using PowerShell. In each folder there are a lot of different files with different extensions. What I want to do is to rename the folder with the *.nfo filename.
Example:
C:\foldertest\TEST\
In this folder these files reside:
JPG.jpg
NFO.nfo
TXT.txt
WAV.wav
After running a script I want the folder to be renamed like the *.nfo:
C:\foldertest\NFO\
I need a solution that works on > 1 folder at a time.
This is what I have (not working o/c):
Get-ChildItem -Path "C:\foldertest\" | Where-Object{$_.PSisContainer} | ForEach-Object -Process {
$new1Name = Get-ChildItem $_ -Filter "*.nfo" | Select-Object -ExpandProperty BaseName
Rename-Item -Path $_.FullName -NewName ($_.Name -replace $new1Name
}
UPDATE:
I am still having problems. The solution (see below) seemed to work at first, but only sometimes. Let's say on 30% of the folders. Then this error happens on the rest:
Rename-Item : Cannot rename because item at 'C:\Users\STOFFES\Desktop\REN\blablablabla' does not exi
st.
At C:\Users\STOFFES\Desktop\REN\REN.ps1:2 char:3
+ Rename-Item (Split-Path $_ -Parent) ($_.BaseName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
Even though there are *.nfo files in most of the folders.
Get-ChildItem -Path "E:\Test\Rename" -Include "*.nfo" -Recurse |
ForEach-Object {
$oldFolder = $_.DirectoryName
# New Folder Name is .nfo Filename, excluding extension
$newFolder = $_.Name.Substring(0, $_.Name.Length - 4)
# Verify Not Already Same Name
if ($_.BaseName.ToUpper() -ne $newFolder.ToUpper()) {
Write-Host "Rename: $oldFolder To: $newFolder"
Rename-Item -NewName $newFolder -Path $oldFolder
}
}
Do you have multiple levels of subfolders? That's most likely why you're getting 'Cannot rename because item does not exist' errors, because you've already renamed a parent folder. If that's the case, you'll need something more complex.