-1

i want to rename all files in a folder. i made a test folder with link files to the original files for the case if something wents wrong. i searched hours on google and made a script with a few code snipplets.

this is my script:

$i = 1
cd "C:\Users\myname\Desktop\test"
get-childitem -filter "*" | %{rename-item $_ -newname ('filename_s01e{0:D3}.lnk' -f $i++)}

when i launch the script i get an error that renaming isn't possible because the item doesn't exist at originalfilename.lnk

i tried to change the filters and the filename but i have no clue why it's missing the items.

thx for help!

user3132608
  • 3
  • 1
  • 2
  • I think the problem is the way you're using the .lnk files. Why not just use the -WhatIf switch? – mjolinor Dec 24 '13 at 14:00
  • Is this essentially what you are trying to do? http://stackoverflow.com/questions/1523043/how-to-loop-through-files-and-rename-using-powershell – beavel Dec 24 '13 at 14:02
  • if i use the whatif switch with the original files, i get the same error. i used the answer from this question as a template: http://stackoverflow.com/questions/18304025/bulk-renaming-of-files-in-powershell-with-sequential-numeric-suffixes – user3132608 Dec 24 '13 at 14:05

1 Answers1

2

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++)
    }
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • thx you helped me alot. I had to upgrade to powershell v3 but now i got it perfectly working with this line: get-childitem | sort-object name | %{ Rename-Item -LiteralPath $_.FullName -NewName ("filename_s01e{0:D3}.lnk" -f $i++) } – user3132608 Dec 25 '13 at 21:30