Reputation: 7228
I have just written a simple function in Powershell
Function Get-Stage
{
$myEnv = Get-Environment
$devEnvs = "D","Dev","Test","T"
$prodEnvs = "P","U","PTA","B"
if($devEnvs -contains $myEnv)
{
return "D"
}
elseif($prodEnvs -contains $myEnv)
{
return "P"
}
}
EDIT
Get-Environment
is a function that reads the registry to find the environment text which can be any string value listed in $devEnvs
and $prodEnvs
. The function will just return either a D
or a P
based on what is returned from Get-Environment
I don't like it. Is there a nice readable, concise way to write it that you can think of?
Upvotes: 0
Views: 120
Reputation: 4838
Well, questions on better ways to write code is very much based on different opinions, but you could do something like the following:
function Get-Stage
{
$environment = Get-Environment
switch ($environment)
{
{$PSItem -in "D","Dev","Test","T"}{
Write-Output "D"
}
{$PSItem -in "P","U","PTA","B"}{
Write-Output "P"
}
default{
Write-Error "Invalid environment value in registry ('$PSItem')"
}
}
}
If you want to support PowerShell v2, just change the switch statement to the following:
switch ($environment)
{
{"D","Dev","Test","T" -contains $_}{
Write-Output "D"
}
{"P","U","PTA","B" -contains $_}{
Write-Output "P"
}
default{
Write-Error "Invalid environment value in registry ('$_')"
}
}
Upvotes: 3
Reputation: 26424
Does this make it any better?
Function Get-Stage
{
$myEnv = Get-Environment;
$envDict = @{
"D" = @("Dev","Test","T");
"P" = @("U","PTA","B")
};
$envDict.Keys | foreach {
$envs = @($_) + $dict[$_];
if($envs -contains $myenv) { return $_; }
}
}
Upvotes: 2