Escaping & in a file path

This topic contains 3 replies, has 3 voices, and was last updated by  Tim Curwick 2 years, 7 months ago.

  • Author
  • #31223

    Steven Ayers

    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

    Chris Wolfenden

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


  • #31229

    Steven Ayers

    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

    Tim Curwick


    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

You must be logged in to reply to this topic.