Public/Manage-SpecEnvironmentVariable.ps1

Function Manage-SpecEnvironmentVariable {

    [CmdletBinding()]

    param (
        [Parameter(Mandatory = $true)]
        [AllowNull()]
        [AllowEmptyString()]
        [string]$VariableName,

        [Parameter(Mandatory = $false)]
        [AllowNull()]
        [AllowEmptyString()]
        [string]$Value,

        [validateset ("Add", "Replace", "Delete") ]
        [string]$Action
    )

    if ($action -eq 'Add') {
        write-host "Adding env var: [$VariableName] with value [$Value]" -ForegroundColor DarkCyan
        $result = Get-SpecEnvironmentVariable -VariableName $VariableName -scope Process
        if ($result -eq $false) {
            write-host "Adding at the [Process] level" -ForegroundColor DarkGray
            $procresult = Set-SpecEnvironmentVariable -VariableName $VariableName -VariableValue $Value -scope Process

            write-host "Adding at the [Machine] level" -ForegroundColor DarkGray
            $machresult = Set-SpecEnvironmentVariable -VariableName $VariableName -VariableValue $Value -scope machine

            write-host "Process complete" -ForegroundColor DarkGreen
        } else {
            write-host "The variable already exists and has the value: [$result] so not adding. To overwrite the value, please use 'Replace' as the action." -ForegroundColor DarkYellow
        }
    }

    if ($action -eq 'Replace') {
        write-host "Replacing env var: [$VariableName] with value [$Value]" -ForegroundColor DarkCyan

        write-host "Replacing at the [Process] level" -ForegroundColor DarkGray
        $procresult = Set-SpecEnvironmentVariable -VariableName $VariableName -VariableValue $Value -scope Process

        write-host "Replacing at the [Machine] level" -ForegroundColor DarkGray
        $machresult = Set-SpecEnvironmentVariable -VariableName $VariableName -VariableValue $Value -scope machine

        write-host "Process complete" -ForegroundColor DarkGreen
    }

    if ($action -eq 'Delete') {
        write-host "Deleting env var: [$VariableName]" -ForegroundColor DarkCyan
        $result = Get-SpecEnvironmentVariable -VariableName $VariableName -scope Process
        if ($result -eq $false) {
            write-host "The env var does not exist to delete" -ForegroundColor DarkGray
        } else {

            write-host "Deleting at the [Process] level" -ForegroundColor DarkGray
            $procresult = Remove-SpecEnvironmentVariable -VariableName $VariableName -scope Process

            write-host "Deleting at the [Machine] level" -ForegroundColor DarkGray
            $machresult = Remove-SpecEnvironmentVariable -VariableName $VariableName -scope machine

            write-host "Process complete" -ForegroundColor DarkGreen
        }
    }
}