Search code examples
powershellreplacerename

Powershell: two options: replace special characters of file names


I don't know Powershell and tend to do most of my fiddling in CMD. I've come across two methods of what I think does the same thing in Powershell (replace an illegal with legal character compatible w/ Windows File Explorer)? I'm wondering if one of the below is recommended over the other? Is either of them really NOT recommended at all?

Get-ChildItem -File -Recurse | Rename-Item -NewName {$_.name -replace "\]", ")"}

Get-ChildItem -File -Recurse | % { Rename-Item -Path $_.PSPath -NewName $_.Name.replace("\]", ")"}

Also wondering why the below two are the way they are. Seems like one would error out.

$_.name -replace

$_.Name.replace

Thanks for any information.


Solution

  • Both methods are Ok to use but the difference is that .Replace is literal replacement, in your example, it will try to find and replace a literal \], whereas -replace uses regular expressions and, if you want to match a literal ] then you need to escape that character with \. See Escaping characters.

    In both examples I would definitely recommend to perform a pre filtering to find only files containing a ]. If you want both to do exactly the same (replace ] for a ) from files) then:

    # With -replace:
    Get-ChildItem -Filter *]* -File -Recurse |
        Rename-Item -NewName { $_.Name -replace '\]', ')' }
    
    # With .Replace:
    Get-ChildItem -Filter *]* -File -Recurse |
        Rename-Item -NewName { $_.Name.Replace(']', ')') }