Reputation: 2298
I have a snippet of Powershell where I need to call an external executable, with a list of switches.
& $pathToExe
--project $project `
--server $server `
--apiKey $key `
Now I need to do something like "if $someVariable -eq $True
then also add --optionalSwitch $someValue
".
How can I do this without a load of repetition? For reference the real exe call is much bigger than this, and the list of optional switches is larger!
Upvotes: 1
Views: 43
Reputation: 24081
How about a hashtable that contains parameters and their values? Like so,
$ht = @{}
$ht.Add('project', 'myProject')
$ht.Add('apikey', $null)
$ht.Add('server', 'myServer')
To build the parameter string, filter the collection by excluding keys without values:
$pop = $ht.getenumerator() | ? { $_.value -ne $null }
Build the command string by iterating the filtered collection
$cmdLine = "myExe"
$pop | % { $cmdLine += " --" + $_.name + " " + $_.value }
# Check the result
$cmdLine
myExe --server myServer --project myProject
Upvotes: 3