PowerShell Cmdlets and Environment Variables
Aug 31st 2007Desmond LeePowerShell
Running Get-ChildItem or any of the variants (alias) such as dir using the following syntax on a PowerShell environment variable may fail under certain circumstances:
PS C:\> gci $env:path
Get-ChildItem : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
At line:1 char:4
+ gci <<<< $env:path
Get-ChildItem : Cannot find path ‘C:\Program Files\Windows Resource Kits\Tools\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\ Wbem;C:\Program Files\Support Tools\;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Program Files\Microsoft Network Monitor 3\;C:\Program File
s\ATI Technologies\ATI Control Panel’ because it does not exist.
At line:1 char:4
+ gci <<<< $env:pathPS C:\>($env:path).length
274
The proper way to do this is to remove the preceding dollar sign whenever such variables are used directly against a cmdlet i.e. dir env:path. Together, $env: is required to qualify the scope of the variable when used by itself at the interactive PowerShell console i.e. $env:path. This is because a similarly named variable can be defined in the same scope ($path). Otherwise, an error will be thrown:
PS C:\> env:path
The term ‘env:path’ is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.
At line:1 char:8
+ env:path <<<<
This aspect of PowerShell is actually documented but may not be very obvious until you start using it as demonstrated.
Technorati tags: PowerShell