Reputation: 3159
I'm on a Win 7 machine using Powershell 4.0
PS C:\> $psversiontable
Name Value
---- -----
PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.42000
BuildVersion 6.3.9600.18728
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
See command line exercise below. The dll exists. The environment variable exists and has the correct path. When I use the the environment variable with Test-Path
, it incorrectly reports $false
. When I use a string literal with Test-Path
, it correctly reports $true
Why does Test-Path
incorrectly report false when I use the environment variable?
PS C:\> dir "C:\Program Files (x86)\Gemalto\NET Smartcard Framework SDK\v2.3.0\bin\SmartCard.Runtime.dll"
Directory: C:\Program Files (x86)\Gemalto\NET Smartcard Framework SDK\v2.3.0\bin
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 1/13/2012 6:57 PM 131072 SmartCard.Runtime.dll
PS C:\> Write-Host $env:GEMALTO_SMARTCARD_DLL
"C:\Program Files (x86)\Gemalto\NET Smartcard Framework SDK\v2.3.0\bin\SmartCard.Runtime.dll"
PS C:\> Test-Path $env:GEMALTO_SMARTCARD_DLL
False
PS C:\> Test-Path "C:\Program Files (x86)\Gemalto\NET Smartcard Framework SDK\v2.3.0\bin\SmartCard.Runtime.dll"
True
Upvotes: 1
Views: 738
Reputation: 22102
As you print Write-Host $env:GEMALTO_SMARTCARD_DLL
, then you can see that environment variable GEMALTO_SMARTCARD_DLL
includes literal "
as part of its value. That is incorrect. You should remove them before passing to Test-Path
: $env:GEMALTO_SMARTCARD_DLL.Trim('"')
, for example.
Note: although "
is invalid character for file system path, it is not invalid character for PowerShell path, as it is not limited for file system only.
New-PSDrive -Name '"C' -PSProvider Variable -Root \
${Program Files (x86)\Gemalto\NET Smartcard Framework SDK\v2.3.0\bin\SmartCard.Runtime.dll"} = 'Value'
Test-Path $env:GEMALTO_SMARTCARD_DLL
Upvotes: 3
Reputation: 19654
Your problem is not due to environment variables (they are just variables in a different drive- Env:
versus Variable:
), but with the contents of your environment variable. If you are creating this variable in cmd, you should use the following syntax:
SET "GEMALTO_SMARTCARD_DLL=C:\Program Files(x86)\.."
Arguments in PowerShell are a bit smarter than batch arguments and passing a variable counts as an argument in its entirety, regardless of its contents.
In your specific case, your variable has quote characters as part of the contents which doesn't make sense to Test-Path
:
PS C:\> $Env:GEMALTO_SMARTCARD_DLL
"C:\Program Files (x86)\Gemalto\NET Smartcard Framework SDK\v2.3.0\bin\SmartCard.Runtime.dll"
You can fix this by fixing the declaration of the environment variable, or you can fix it in your code:
$GEMALTO_SMARTCARD_DLL = $Env:GEMALTO_SMARTCARD_DLL -replace '^"' -replace '"$'
Upvotes: 0