Question:
1 2 3 4 5 |
ls *.gif | Foreach { $newname = $_.Name -replace '\[','' -replace '\]','' write-host $_.Name $newname move-Item -Path $_.Name -Destination $newname; } ls *.gif |
So while trying to help someone rename files with [], I found out move-item doesn’t work in a loop. It seems to work just fine outside the loop.
Ideas?
Answer:
Update: Based on the comment below, I want to clarify this: The special characters in the file names require you to use -LiteralPath parameter. -Path cannot handle those characters. Outside a loop, -Path works since you are escapting the special characters using `. This isn’t possible when walking through a collection.
In a loop, you need to use -LiteralPath parameter instead of -Path.
1 2 3 4 5 6 7 |
-LiteralPath Specifies the path to the current location of the items. Unlike Path, the value of LiteralPath is used exactly as it is typed. **No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks.** Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences. |
SO, this will be:
1 2 |
GCI -Recurse *.txt | % { Move-Item -LiteralPath $_.FullName -Destination "SomenewName" } |