Skip to content

Instantly share code, notes, and snippets.

@steviecoaster
Last active February 17, 2021 22:44
Show Gist options
  • Save steviecoaster/7597ad7e43ebf2c28ab66c37a4dc0df2 to your computer and use it in GitHub Desktop.
Save steviecoaster/7597ad7e43ebf2c28ab66c37a4dc0df2 to your computer and use it in GitHub Desktop.
Sets a System level environment variable to machine, currentuser, or process scope.
function Set-EnvironmentVariable {
<#
.SYNOPSIS
Sets a system environment variable
.DESCRIPTION
Sets an environment variable in either machine, currentuser, or process scope
.PARAMETER Scope
The scope to set variable too
.PARAMETER Name
The name of the env variable
.PARAMETER Value
The value of the environment variable
.EXAMPLE
Set-EnvironmentVariable -Scope Machine -Name Test -Value 'ThisIsCool'
.NOTES
Name and Value must be below 32767 characters. Anything higher will cause an error when setting the variable.
#>
[cmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateSet('Machine', 'User', 'Process')]
[String]
$Scope,
[Parameter(Mandatory)]
[ValidateScript( {
if ($_.Length -gt 32767) {
throw "Parameter value too long. Must be below 32767 characters"
}
else { $true }
})]
[String]
$Name,
[Parameter(Mandatory, ValueFromPipeline)]
[ValidateScript( {
if ($_.Length -gt 32767) {
throw "Parameter value too long. Must be below 32767 characters"
}
else { $true }
})]
[String]
$Value
)
process {
try {
[Environment]::SetEnvironmentVariable($Name, $Value, $Scope)
Write-Output 'Environment variable successfully created. You will need to re-open PowerShell to pick it up.'
}
catch { $_.Exception.message }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment