Categories

COM pt 4

If you have been following along so far you may be thinking that you can use

ls env:

to view the environmental variables.

True.

But if you compare the output of part 3, the PowerShell enc: drive and getting the environmental variables via WMI you will find that they aren’t identical.

The point of this post is to show that we can combine what we are learning about the WScript objects with “pure” PowerShell.

Look at the path variable – on my test machine I get

PS> $env:path
%SystemRoot%\system32\WindowsPowerShell\v1.0\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\jZip;C:\Program Files\TortoiseHg\;C:\Program Files\Windows Live\Shared

 

OK. Now notice the first entry %systemroot%. We can’t resolve that directly in PowerShell but what we can do is this

001
002
003
004
005
006
007
008
009
010
011
012
013
014

function resolve-envar {
param([string]$var
)
 
$wshell = New-Object -ComObject "WScript.Shell"
 $wshell.ExpandEnvironmentStrings("$var"
)
}


$data = $env:path -split "\\"
0..$($data.length -1) | foreach
 {
 
if ($data[$($_)] -match "%.*%"
) {
 
$data[$($_)] = resolve-envar $data[$($_)]
 }
}

$path = $data -join "\"
$path

 

We get the path and split it at the \ folder delimiters.  We need to use \\ as \ is interpreted as an escape character. We examine each element in the path -  a range operator is less typing than a for loop – and if it is of the form %…….% we use the resolve-envar function to expand it.

We can then stick the bits back together again and display the path.

Not something we are likely to use every day but it does show how we can drop bits of functionality into our scripts when they are the easiest way to do things.

One Response to COM pt 4

Leave a Reply