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

标签 powershell

我有一个Powershell片段,我需要在其中调用带有开关列表的外部可执行文件。

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

现在,我需要执行类似“if $someVariable -eq $True然后还添加--optionalSwitch $someValue”的操作。

没有重复的负载怎么办?作为引用,真正的exe调用远大于此,并且可选开关的列表也更大!

最佳答案

包含参数及其值的哈希表如何?像这样

$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

关于powershell - 如何在Powershell中为可执行文件构建参数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45031231/

相关文章:

powershell - 将参数字符串转换为 Here String

Powershell,从txt文件中读取并格式化数据(删除行,删除它们之间的空格)

powershell - 如何在 Powershell 中指定复杂的发布者名称?

python - Powershell '>' 运算符,更改编码?

windows - Get-ChildItem 相当于 DIR/X

powershell - 在 PowerShell 中将 Hashtable 与 switch case 结合使用

windows - 在命令提示符 (cmd.exe) 中运行 psm1 PowerShell 脚本?

azure - 为什么azure子网没有subnet.id参数

powershell - 如何使用 ARM Powershell 为新创建的虚拟机分配网络接口(interface)?

regex - 使用 RegEx 与 PowerShell 匹配