Escaping & in a file path

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Tim Curwick Tim Curwick 1 year, 7 months ago.

  • Author
    Posts
  • #31223
    Profile photo of Steven Ayers
    Steven Ayers
    Participant

    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
    Profile photo of Chris Wolfenden
    Chris Wolfenden
    Participant

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

    Chris

  • #31229
    Profile photo of Steven Ayers
    Steven Ayers
    Participant

    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
    Profile photo of Tim Curwick
    Tim Curwick
    Participant

    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
    

You must be logged in to reply to this topic.