Author Posts

February 19, 2014 at 10:38 am

Is there a "best practice" for getting environment values such as the local computer name?

I've found each of the following work, and I've found web sites that recommend each one, but I've no idea which would be considered a "best practice".

$env:computername

get-content env:computername

[environment]::machinename

February 19, 2014 at 10:41 am

I tend to use $env:COMPUTERNAME because its less typing and tab completion works

February 19, 2014 at 10:43 am

I don't know about best practices, but I mostly like $env:COMPUTERNAME for its convenience; it can be embedded directly in a double-quoted string without the need for subexpressions.

That said, if you specifically want to work with a System environment variable instead of a Process variable, you'll need to use methods in the [System.Environment] class. For example, these two commands will almost certainly return different values:

$env:Path

[System.Environment]::GetEnvironmentVariable('Path', [System.EnvironmentVariableTarget]::Machine)