如何在Powershell中为可执行文件构建参数列表?

时间:2017-07-11 09:56:49

标签: powershell

我有一段Powershell,我需要调用外部可执行文件,并附带一个开关列表。

& $pathToExe 
        --project $project `
        --server $server `
        --apiKey $key `

现在我需要执行类似"如果$someVariable -eq $True,则还要添加--optionalSwitch $someValue"。

如果没有重复,我怎么能这样做?作为参考,真正的exe调用远大于此,可选开关列表更大!

1 个答案:

答案 0 :(得分:3)

包含参数及其值的哈希表怎么样?像这样,

$ht = @{}
$ht.Add('project', 'myProject') 
$ht.Add('apikey', $null) 
$ht.Add('server', 'myServer')

要构建参数字符串,请通过排除没有值的键来过滤集合:

$pop = $ht.getenumerator() | ? { $_.value -ne $null }

通过迭代过滤的集合

来构建命令字符串
$cmdLine = "myExe"
$pop | % { $cmdLine += " --" + $_.name + " " + $_.value }
# Check the result
$cmdLine
myExe --server myServer --project myProject