The PowerShell-idiomatic approach is to:
Define a command (function) that adheres to PowerShell's
<verb>-<noun>naming convention, using one of the approved verbsapproved verbs.Use an alias to provide another, typically shorter, name for the command, that isn't bound by this convention.
Using
-split, the string splitting operatorstring splitting operator, limiting the number of resulting tokens to2, allows you to split each name-value pair into its constituent parts, and theEnv:driveEnv:drive can be used to define a process-scoped environment variable for each pair.Given that the
exportbuiltin in POSIX-compatible shells such as Bash accepts multiple<name>=<value>pairs (e.g.export FOO='bar none' BAZ=2), so does the function below.- Caveat: POSIX-compatible shells allow defining environment variables without a value (e.g.
export FOO), which PowerShell and .NET do not support: assigning$nullor''invariably undefines (removes) an environment variable there.
Therefore, the function below only accepts<name>=<value>pairs, and reports a non-terminating error if a given argument lacks an=or a value thereafter.
- Caveat: POSIX-compatible shells allow defining environment variables without a value (e.g.
Set-Alias export Set-EnvironmentVariableByNameValuePair
function Set-EnvironmentVariableByNameValuePair {
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromRemainingArguments)]
[string[]] $NameValuePair
)
process {
foreach ($pair in $NameValuePair) {
$name, $value = $pair -split '=', 2
if (-not $name -or -not $value) { Write-Error "Not in <name>=<value> format: `"$pair`". For technical reasons, you must supply a value."; continue }
Set-Content Env:$name $value
}
}
}
Note:
The above is more permissive than POSIX-compatible shells with respect to the names of environment variables - even though names that do not adhere to the constraints spelled out below are supported by the underlying platforms themselves.
If you want to enforce the same name constraints that Bash does, insert the following before the
Set-Contentcall:if ($name -notmatch '^[a-z_]\w*$') { Write-Error "Invalid name: $name"; continue }See also:
- GitHub issue #3316, which asks for PowerShell to support the / something like the concise syntax that POSIX-compatible shells offer for defining child-process-scoped environment variables (e.g.
FOO='bar none' BAZ=2 some_utility ...)
- GitHub issue #3316, which asks for PowerShell to support the / something like the concise syntax that POSIX-compatible shells offer for defining child-process-scoped environment variables (e.g.