PowerShell运行exe文件并将参数作为字符串变量传递

b5lpy0ml  于 2022-11-29  发布在  Shell
关注(0)|答案(1)|浏览(173)

我正在创建一个power shall脚本来运行带有参数的exe文件。参数列表的构造方式是,如果参数的值为空或null,则不应传递参数
下面是我的脚本

$runnerCommand = " "
[string]$splitRun = "20:1"
[string]$maxTestWorkers = "777"
[string]$retryTimes = "9"
[string]$testFilterInXmlFormat = "<filter><cat>XX</cat></filter>"

#$runnerCommand += '--testDllPath ' + $testDllPath + " "

if ($splitRun){
    $runnerCommand+= "--splitRun '$splitRun' "
}

if ($maxTestWorkers){
    $runnerCommand+= "--maxTestWorkers '$maxTestWorkers' "
}

if ($retryTimes){
    $runnerCommand+= "--retryTimes '$retryTimes' "
}

if ($testFilterInXmlFormat){
    $runnerCommand+= "--testFilterInXmlFormat '$testFilterInXmlFormat' "
}

$cmdPath = "C:\AutoTests\TestAutomation.Runner\bin\Debug\TestAutomation.Runner.exe"

& $cmdPath --testDllPath C:/AutoTests/Build/TestAutomation.TestsGUI.dll $runnerCommand

看起来PowerShell在最后一行代码中的$runnerCommand之前执行了一个“新行”,导致不传递来自$runnerCommand的参数
请建议如何解决此问题。
我尝试了不同的方法

bjp0bcyl

bjp0bcyl1#

你现在把所有的参数作为一个字符串传递。你应该使用一个数组,每个参数作为一个单独的元素。我不能测试这个,但是类似这样的东西应该可以工作:

[string]$splitRun = "20:1"
[string]$maxTestWorkers = "777"
[string]$retryTimes = "9"
[string]$testFilterInXmlFormat = "<filter><cat>XX</cat></filter>"

$runnerArgs = @(
    '--testDllPath', 'C:/AutoTests/Build/TestAutomation.TestsGUI.dll'
    if ($splitRun) {
        '--splitRun', $splitRun
    }
    if ($maxTestWorkers) {
        '--maxTestWorkers', $maxTestWorkers
    }
    if ($retryTimes) {
        '--retryTimes', $retryTimes
    }
    if ($testFilterInXmlFormat) {
        '--testFilterInXmlFormat', $testFilterInXmlFormat
    }
)

$cmdPath = "C:\AutoTests\TestAutomation.Runner\bin\Debug\TestAutomation.Runner.exe"

& $cmdPath $runnerArgs

请注意,PowerShell允许在数组子表达式运算符(@())中使用表达式,包括if-表达式。

相关问题