Skip to content

Instantly share code, notes, and snippets.

@codecontemplator
Created November 25, 2017 20:49
Show Gist options
  • Save codecontemplator/f13717eabdac1d0cab60e5d120ab617f to your computer and use it in GitHub Desktop.
Save codecontemplator/f13717eabdac1d0cab60e5d120ab617f to your computer and use it in GitHub Desktop.
A way of handling settings / configuration parameters in powershell (experimental)
function Merge($x, $y)
{
$y.GetEnumerator() | % { $x[$_.Name] = $_.Value }
return $x
}
function Get-Settings
{
[CmdletBinding()]
param(
[Parameter(Position=0, ValueFromPipeline=$true)]
[hashtable]
$Current = @{},
[Parameter(ParameterSetName='default')]
[hashtable]
$Explicit,
[Parameter(ParameterSetName='file')]
[string]
$Path,
[Parameter(ParameterSetName='environment')]
[switch]
$Enviroment,
[Parameter(ParameterSetName='environment')]
[string]
$Prefix = ""
)
process
{
if ($Explicit)
{
Merge $Current $Explicit
}
elseif ($Path)
{
$update = @{}
$json = Get-Content $Path | ConvertTo-Json
$json.psobject.properties | ForEach { $update[$_.Name] = $_.Value }
Merge $Current $update
}
elseif ($Environment)
{
$Current.Keys | ForEach {
$envVarName = "env:\$Prefix$_"
if (Test-Path $envVarName) {
$Current[$_] = (Get-Item -Path $envVarName).Value
}
}
}
}
}
Get-Settings -Explicit @{
enviroment = "test"
key = "hrr9y948u49857h98"
} |
Get-Settings -Path $PSScriptRoot\settings.json |
Get-Settings -Enviroment
#environment -prefix "compliance_test"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment