Search code examples
powershellpathoutputcopy-item

PowerShell Returning "False" for Test-Path "C$\Program Files (x86)"


When attempting to copy a file to a directory via-

Copy-Item $Source -Destination "C$\Program Files (x86)" -Recurse -EA Continue -EV +PushFailures

I'm unable to do so. So I tried testing to see if PowerShell is even seeing the directory-

Test-Path "C$\Program Files (x86)"

and it returns "False" even though it's clearly there.

What am I doing wrong here and how can I correct it? I read about "$env:programfiles" although I'm not sure how to implement that into a string variable.

Thanks in advance.


Solution

  • I'm not used to using C$\Program Files (x86) in that context since it is usually referenced in remote administration shares like \\Computername\C$\Program Files (x86). Did you mean to just use C:\Program Files (x86)?

    Part of the issue is that $ is a reserved character in PowerShell and need to be escaped in strings. Two ways to do this with what you have:

    -Destination "C`$\Program Files (x86)"
    -Destination 'C$\Program Files (x86)'
    

    I feel though that this will not work. If you just want the local path of program files then this would help you include the Environment variable as you suggested

    -Destination "$env:ProgramFiles"
    -Destination "${env:ProgramFiles(x86)}"
    

    If the path contain both string elements and variables then you need to ensure that they are expanded properly by using a sub-expression

    -Destination "$($env:ProgramFiles)\Internet Explorer"