79182706

Date: 2024-11-12 21:12:40
Score: 1
Natty:
Report link

Thanks to @nc1943 above for their excellent answer. I wanted to set system-level environmental variables and also hit a couple of minor errors when trying to use the code above. I've tweaked it and if run in an Admin PowerShell session it successfully imports the variables:

param(
    [string]$Path,
    [switch]$Verbose,
    [switch]$Remove,
    [switch]$RemoveQuotes
)

$variables = Get-Content -Path $Path | Select-String -Pattern '^\s*[^\s=#]+=[^\s]+$'

foreach ($var in $variables) {
    $keyVal = $var -split '=', 2
    $key = $keyVal[0].Trim()
    if ($RemoveQuotes) {
        $val = $keyVal[1].Trim("'").Trim('"')
    } else {
        $val = $keyVal[1]
    }
    if ($Remove) {
        [Environment]::SetEnvironmentVariable($key, '', [System.EnvironmentVariableTarget]::Machine)
    } else {
        [Environment]::SetEnvironmentVariable($key, $val, [System.EnvironmentVariableTarget]::Machine)
    }
    if ($Verbose) {
        "$key=$([Environment]::GetEnvironmentVariable($key, [System.EnvironmentVariableTarget]::Machine))"
    }
}
Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @nc1943
  • Low reputation (1):
Posted by: EDIflyer