A lot of the time when working in DevOps, documentation and code snippets from colleagues will be based on bash. Most of those same commands work seamlessly in PowerShell; but setting environment variables doesn't; e.g. export DEMO_CLIENT_ID="ff3b7b84-e041-4e76-993e-239930808aa7"
.
I've written the below function so I can more easily just copy-paste these snippets and have them work without needing a rewrite:
Function Export {
$regex = [System.Text.RegularExpressions.Regex]::new('^\s*([^=]+?)\s*=(.*)$')
$result = $regex.Match(($args -join ' '))
if (!$result.Success) {
throw "Could not set an environment variable based on [$($args -join ' ')]"
}
[Environment]::SetEnvironmentVariable($result.Groups[1].Value, $result.Groups[2].Value)
}
This works well for most real world examples I've hit so far... but I'm sure there are gotchas lurking (e.g. I know that multiple spaces will be squashed to a single space when the split arguments are re-joined... which may be an issue in some scenarios).
Is there a better approach to this, or are there improvements I can make to avoid this and similar/unforeseen pitfalls?
Note: I know the function name doesn't meet best practices (i.e. verb-noun naming)... My only use case for this function is to simulate the export
command; so I figured giving it a verb noun name and then aliasing that was just adding complexity with no benefit.
export
in pwsh: github.com/PowerShell/PowerShell/issues/20475 \$\endgroup\$DEMO_CLIENT_ID="ff3b7b84-e041-4e76-993e-239930808aa7"
string come from? What I mean: why not using the native hash table syntax:Export @{ DEMO_CLIENT_ID="ff3b7b84-e041-4e76-993e-239930808aa7"; Name="Value" }
? \$\endgroup\$