Reputation: 23
$folderpath = 'E:\BOOKS\Python\python\python'
$items = Get-ChildItem -Recurse $folderpathc *_pdf
foreach( $i in $items) { Rename-Item E:\BOOKS\Python\python\python\$i E:\BOOKS\Python\python\python\$i.pdf }
Hi, I tried to rename the file under a folder using above command but not able to do and got below error.
Rename-Item : Cannot rename because item at 'E:\BOOKS\Python\python\python\book_pdf' does not exist.
At line:1 char:37
+ foreach( $i in $items) { Rename-Item <<<< E:\BOOKS\Python\python\python\$i E:\BOOKS\Python\python\python\$i.pdf }
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
Upvotes: 2
Views: 11485
Reputation: 52699
Looks like you want to change all '_pdf' to '.pdf', if so this is a pretty easy way to do it.
ls -Path 'E:\BOOKS\Python\python\python' -Filter *_pdf |
ForEach-Object {$_ | Rename-Item -NewName $_.Name.Replace('_pdf', '.pdf')}
Upvotes: 9
Reputation: 36342
You're over complicating things. Don't re-type out the path name to the file, use the FullName property already provided by the Get-ChildItem cmdlet. Then just use a substring of the BaseName property to remove the last 4 characters, and add ".pdf" to the end.
$folderpath = 'E:\BOOKS\Python\python\python'
$items = Get-ChildItem -Recurse $folderpathc *_pdf
foreach( $i in $items) {
Rename-Item $i.FullName ($i.basename.substring(0,$i.BaseName.length-4)+".pdf")
}
Upvotes: 0