Escaping & in a file path

Welcome Forums General PowerShell Q&A Escaping & in a file path

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
3 years, 1 month ago.

  • Author
    Posts
  • #31223

    Participant
    Points: 0
    Rank: Member

    So, I am trying to run:

    $Path = "C:\Test & Test\Hello.txt"
    $NewName = "Goobye.txt"
    Rename-Item $Path -NewName $NewName
    

    Which gives me an "illegal characters in path"

    Is there any way I can make this variable escape the & or let is accept this, which im guessing is causing the problem?
    This is inside a foreach loop, so it must be in a var!

  • #31224

    Participant
    Points: 0
    Rank: Member

    This seems to work fine for me (Win 7 – PSVersion 5).

    Chris

  • #31229

    Participant
    Points: 0
    Rank: Member

    Okay, I have actually tested it on my client machine and it's fine – the computer is using PowerShell 3.0 that this is being used for this – think that could be causing the issue?

    Unfortunately, we can't upgrade as it's a client PC, and I cant run this on my machine as it's all tied up with mapped drives and SharePoint etc...

    Does anyone know if the PS version could be the cause of of this issue?

  • #31240

    Participant
    Points: 5
    Rank: Member

    Steven,

    Many commands which take a -Path parameter will alternatively take a -LiteralPath parameter. This helps considerably with certain characters. Not sure if it will help in your case, but give it a try.

    $Path = "C:\Test & Test\Hello.txt"
    $NewName = "Goobye.txt"
    Rename-Item -LiteralPath $Path -NewName $NewName
    

The topic ‘Escaping & in a file path’ is closed to new replies.