Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

move-item doesn't work in loop

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?

like image 379
Tigertoy Avatar asked Mar 16 '11 16:03

Tigertoy


1 Answers

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.

-LiteralPath <string[]>
    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:

GCI -Recurse *.txt | % { Move-Item -LiteralPath $_.FullName -Destination "SomenewName" }
like image 79
ravikanth Avatar answered Sep 20 '22 16:09

ravikanth