在运行外部可执行文件时,您有几个选项。
$command = '\\netpath\restart.exe'
$params = '/t:21600', '/m:360', '/r', '/f'
& $command @params
这个方法本质上会加入你的数组作为可执行文件的参数。这使您的参数列表更清晰,并且可以重写为:
$params = @(
'/t:21600'
'/m:360'
'/r'
'/f'
)
这通常是我最喜欢的解决问题的方法。
一次调用带有参数的可执行文件
如果您在参数、路径等中没有空格,则不一定需要有变量甚至 call operator (&)。
\\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()
}
}