When you use Rename-item $_
your sending setting the 1st positional parameter, -Path
, equal to $_
casted as a string(which will be the filename). The problem with -Path
is that it doesn't support special characters very vell, which I'm guessing you have in your filename.
If you had used $_ | Rename-Item
, the cmdlet would have linked up the FullName
property with -LiteralPath
parameter in the cmdlet. -LiteralPath
is an alternative to -Path
which works better with special characters, and because of that it's used as default for parameter-binding in pipelines.
By using the approach below, we will tell your script to use -LiteralPath
and link it with the full path of the file, FullName
, which should solve your problems. This is the recommended way to use the cmdlet if you're using a foreach-loop instead of Get-ChildItem | Rename-Item
.
Also, if you want all files in a folder, you don't need to use filter. Try the sample below.
$i = 1
cd "C:\Users\myname\Desktop\test"
get-childitem | %{ Rename-Item -LiteralPath $_.FullName -NewName ("filename_s01e{0:D3}.lnk" -f $i++) }
You could also include the folderpath in the Get-ChildItem
cmdlet and create your variable in the foreach-loop like:
Get-ChildItem -Path "C:\Users\myname\Desktop\test" |
% -Begin { $i = 1 } -Process {
Rename-Item -LiteralPath $_.FullName -NewName ("filename_s01e{0:D3}.lnk" -f $i++)
}