Occasionally you see scripts that use Select-Object to append information to existing objects. This can look similar to the code below:

Get-Process | 
    Select-Object -Property *, Sender|
    ForEach-Object { 
        $_.Sender = $env:COMPUTERNAME
        $_
    }

It does work, but Select-Object creates a complete object copy, so this approach is slow and changes the object type. You’ll notice that PowerShell no longer outputs the process objects with the usual table design because of this.

If you’d like to set environment variables, the env: drive provides access only to the process set of environment variables. To set variables on user or machine level, try this function:

function Set-EnvironmentVariable
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)][String]
        $VariableName,
        
        [Parameter(Mandatory)][String]
        $VariableValue,
        
        [Parameter(Mandatory)][EnvironmentVariableTarget]
        $Target        
    )
    
   [Environment]::SetEnvironmentVariable($VariableName, $VariableValue, $Target)
}

Note how the parameter $Target uses a special data type named “EnvironmentVariableTarget”. When you run the function in PowerShell ISE or another editor with IntelliSense, the –Target parameter provides you with the valid choices “Process”, “User”, and “Machine”.

This is how you’d create an environment variable named “Test” with value 12 in the user scope:

 
PS C:\> Set-EnvironmentVariable -VariableName test -VariableValue 12 -Target User

PS C:\>  
 

Twitter This Tip! ReTweet this Tip!

Anonymous