当运行外部可执行文件时,您有几个选项。
Splatting是一种将参数作为哈希表传递给命令的技术。这使得代码更加易于阅读和维护。
$command = '\\netpath\restart.exe'
$params = '/t:21600', '/m:360', '/r', '/f'
& $command @params
这种方法本质上将您的数组作为参数加入到可执行文件中。这样做可以使您的参数列表更加清晰,并且可以重写为:
$params = @(
'/t:21600'
'/m:360'
'/r'
'/f'
)
这通常是我解决问题的最喜欢方法。
一次性使用参数调用可执行文件
如果参数、路径等没有空格,您不一定需要变量甚至调用运算符(&
)。
\\netpath\restart.exe /t:21600 /m:360 /r /f
这是我第二选择的方法,因为它可以更好地控制最终进程。有时可执行文件会生成子进程,而调用运算符在脚本中继续执行之前不会等待进程结束。这种方法可以让您对此进行控制。
$startParams = @{
FilePath = '\\netpath\restart.exe'
ArgumentList = '/t:21600', '/m:360', '/r', '/f'
Wait = $true
PassThru = $true
}
$proc = Start-Process @startParams
$proc.ExitCode
这是我知道的最后一种方法,直接使用Process
.NET类。如果需要更多控制进程,例如收集其输出,则可以使用此方法:
try {
$proc = [System.Diagnostics.Process]::Start([System.Diagnostics.ProcessStartInfo]@{
FileName = "\\netshare\restart.exe"
Arguments = '/t:21600 /m:360 /r /f'
CreateNoWindow = $true
UseShellExecute = $false
RedirectStandardOutput = $true
})
$output = $proc.StandardOutput
$output.ReadToEnd()
} finally {
if ($null -ne $proc) {
$proc.Dispose()
}
if ($null -ne $output) {
$output.Dispose()
}
}
Start-Process
,但你的示例也可以工作。 - TobyU$Command
周围加上"
。 - Bill_Stewart"$($Command.ToString())"
:PPS: 该语句为代码中的一条输出语句。 - Maximilian Burszley