开发者

PowerShell: combining paths using a variable

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?


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


That is weird and looks like a bug. Actually it is resolving the $env:programfiles variable and appending the rest of the string - which in this case just happens to be (x86).

This will work though:

$f =  ${env:ProgramFiles(x86)} + '\sometextfile.txt'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜