Public/Set-SpecEnvironmentVariable.ps1
Function Set-SpecEnvironmentVariable { <# .SYNOPSIS Sets the specified environment variable to the provided value at the specified scope (User, Machine, or Process). .DESCRIPTION The Set-SpecEnvironmentVariable function sets the specified environment variable to the provided value at the specified scope (User, Machine, or Process). If the variable does not exist, it creates a new one. .PARAMETER VariableName Specifies the name of the environment variable to set. .PARAMETER VariableValue Specifies the value to set for the environment variable. .PARAMETER Scope Specifies the scope of the environment variable. Valid values are "User" (user-level variable), "Machine" (system-level variable), or "Process" (variable available only to the current process). .EXAMPLE Set-SpecEnvironmentVariable -VariableName "SampleVar" -VariableValue "SampleValue" -Scope "Machine" Sets the environment variable named "SampleVar" to "SampleValue" at the machine level. .EXAMPLE Set-SpecEnvironmentVariable -VariableName "TEMP" -VariableValue "C:\Temp" -Scope "User" Sets the environment variable named "TEMP" to "C:\Temp" at the user level. .OUTPUTS Integer. Returns 0 if the setting is successful. Returns 2 if an error occurs while setting the environment variable. .NOTES Author : owen.heaume Version : 1.0 #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [AllowNull()] [AllowEmptyString()] [string]$VariableName, [Parameter(Mandatory = $true)] [AllowEmptyString()] [AllowNull()] [string]$VariableValue, [validateset ("User", "Machine", "Process") ] [string]$scope ) try { write-verbose "Adding [$VariableName] with a value of [$VariableValue] at the $scope level" [System.Environment]::SetEnvironmentVariable($VariableName, $VariableValue, [System.EnvironmentVariableTarget]::$scope) write-verbose "Setting at scope: $scope" return 0 } catch { Write-Warning "An error occurred while setting the variable at the $scope level: $_" return 2 } } |