Set-EnvironmentVariable
Windows: Sets or removes an environment variable in a specified scope
#Requires -Version 5.1
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[string]$Name,
[string]$Value = "",
[ValidateSet('Machine', 'User')]
[string]$Scope = 'Machine',
[string]$ComputerName = $env:COMPUTERNAME,
[pscredential]$Credential
)
Process {
try {
$scriptBlock = {
Param($VarName, $VarValue, $VarScope)
[System.Environment]::SetEnvironmentVariable($VarName, $VarValue, $VarScope)
$val = [System.Environment]::GetEnvironmentVariable($VarName, $VarScope)
[PSCustomObject]@{
Name = $VarName
Value = $val
Scope = $VarScope
Status = if ($val) { "Configured" } else { "Removed" }
}
}
if ($ComputerName -ne $env:COMPUTERNAME) {
$invokeParams = @{
'ComputerName' = $ComputerName
'ScriptBlock' = $scriptBlock
'ArgumentList' = @($Name, $Value, $Scope)
'ErrorAction' = 'Stop'
}
if ($null -ne $Credential) {
$invokeParams.Add('Credential', $Credential)
}
$result = Invoke-Command @invokeParams
}
else {
$result = &$scriptBlock -VarName $Name -VarValue $Value -VarScope $Scope
}
$result | Add-Member -MemberType NoteProperty -Name ComputerName -Value $ComputerName -PassThru
Write-Output $result
}
catch {
throw
}
}Specifies the name of the environment variable.
Specifies the value of the environment variable. An empty string removes the variable.
Specifies the scope: Machine or User. Defaults to Machine.
Specifies the name of the target computer. Defaults to the local computer.
Specifies a PSCredential object for remote connection.