I'm basically trying to trim() any filenames that have a leading or trailing space at the end of the name. This is the code I've got so far
$foldersToCheck = "$env:userprofile\documents", "$env:userprofile\pictures", "$env:userprofile\desktop"
foreach ($folder in $foldersToCheck) {
get-childitem -path $folder -recurse | foreach-object {
if ($_.name.startswith(" ") -or $_.name.endswith(" ")) {
$newName = $_.name.trim()
rename-item -path $_ -newName $newname
}
}
}
If I create a test file (c:\users\someusername\desktop\ test.txt), then I receive this error
rename-item : Cannot rename because item at ' test.txt' does not exist.
At line:6 char:13
+ rename-item -path $_ -newName $newname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
So, it looks like it found the file that needs to be renamed, but then says it doesnt exist.
The problem here is that PowerShell resolves $_
to just the file name when attempting to convert it to a string it can bind to -Path
.
Explicitly pass the full path of the file and it'll work:
Rename-Item -Path $_.FullName -NewName $newname
Alternatively, pipe the $_
file object to Rename-Item
and PowerShell will automatically figure out that it needs to bind $_.FullName
to Rename-Item
's -LiteralPath
parameter:
$_ |Rename-Item -NewName $newname
You can also turn the whole loop into a single pipeline, and then take advantage of a pipeline-bound expression against -NewName
:
$foldersToCheck |Get-ChildItem -Recurse |Rename-Item -NewName { $_.Name.Trim() }
If the existing Name
and the -NewName
values are the same, Rename-Item
will just leave the files alone anyway :)