Categories

Scripting Games 2012 comments: #16 reading environmental variables

Windows maintains a set of environmental variables. Some, but not all, can be seen via the env: PowerShell drive

Get-ChildItem -Path env:

You can also use WMI to see some of the variables

Get-WmiObject -Class Win32_Environment | ft Name, VariableValue –a

 

Now how do you read them in your scripts?

 

I noticed a lot of people doing this

$name = (Get-Item env:\Computername).Value

 

It works but its a bit long winded.  A better method is this

$name = $env:COMPUTERNAME

$env: is the environment provider surfaced as a namespace

You can also use this technique with other providers e.g.

PS> $variable:MaximumAliasCount
4096

It doesn’t work with all providers e.g. the registry.

Leave a Reply