1

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!

2
  • Will the exe accept arguments in the form --project:$project --server:$server (: rather than spaces between switches and arguments) - if so, it's trivial with splatting Commented Jul 11, 2017 at 10:13
  • It accepts '=' for some arguments, but there are others which don't have any associated value like --debug. Would your suggestion still work for those? Commented Jul 11, 2017 at 10:19

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.