Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: combining paths using a variable

Tags:

powershell

This must be something obvious, but I can't get this to work.

I'm trying to build a variable that should contain the path to an existing file, using an environment variable ($env:programfiles(x86)). However I keep getting errors, and I fail to see why.

This works fine (if the file exists):

PS C:\> $f = "C:\Program Files (x86)" + '\sometextfile.txt'
PS C:\> $f
C:\Program Files (x86)\sometextfile.txt
PS C:\> gci $f
    Directory: C:\Program Files (x86)
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        13/12/2010     14:03          0 sometextfile.txt
PS C:\>

However, this does not:

PS C:\> "$env:programfiles(x86)"
C:\Program Files(x86)
PS C:\> $f = "$env:ProgramFiles(x86)" + '\sometextfile.txt'
PS C:\> $f
C:\Program Files(x86)\sometextfile.txt
PS C:\> gci $f
Get-ChildItem : Cannot find path 'C:\Program Files(x86)\sometextfile.txt' because it does not exist.
At line:1 char:4
+ gci <<<<  $f
    + CategoryInfo          : ObjectNotFound: (C:\Program Files(x86)\sometextfile.txt:String) [Get-ChildItem], ItemNot
   FoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

What's happening, and how do I fix it?

like image 520
jeroenh Avatar asked Dec 13 '10 13:12

jeroenh


1 Answers

Here is what is going on...

In any Windows PowerShell path empty characters or spaces need to be surrounded with a set of quotes or brackets. The PowerShell environment variable for the C:\Program Files (x86) is ${env:ProgramFiles(x86)}, not $env:ProgamFiles(x86) since PowerShell needs to escape the empty spaces in the real path.

If you use the '${env:ProgramFiles(x86)}' explicit environment variable, it works perfectly.


This won't work...

PS C:\> cd "$env:programfiles(x86)"
Set-Location : Cannot find path 'C:\Program Files(x86)' because it does not e
At line:1 char:3
+ cd <<<<  "$env:programfiles(x86)"
+ CategoryInfo          : ObjectNotFound: (C:\(x86):String)
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.

or this...

PS C:\> $env:ProgramFiles(x86)
Unexpected token '(' in expression or statement.
At line:1 char:19
+ $env:ProgramFiles( <<<< x86)
+ CategoryInfo          : ParserError: ((:String) [], Parent
+ FullyQualifiedErrorId : UnexpectedToken

But this works great...

PS C:\> ${env:ProgramFiles(x86)}
C:\Program Files (x86)
PS C:\> $f = "${env:ProgramFiles(x86)}" + "\sometextfile.txt"
PS C:\> $f
C:\Program Files (x86)\sometextfile.txt
PS C:\> gci $f
Directory: C:\Program Files (x86)


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        12/13/2010   8:58 AM          0 sometextfile.txt
like image 106
thoughtpunch Avatar answered Nov 16 '22 03:11

thoughtpunch