运行外部可执行文件时,您有几个选项。
泼溅 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-5.1
$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
Start-Process https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-5.1
这是我的第二个选择,因为它让我对最终过程有更多的控制权。有时可执行文件会产生子进程,并且您的调用操作员不会等待进程结束就继续执行脚本。这个方法可以让你控制它。
$startParams = @{
FilePath = '\\netpath\restart.exe'
ArgumentList = '/t:21600', '/m:360', '/r', '/f'
Wait = $true
PassThru = $true
}
$proc = Start-Process @startParams
$proc.ExitCode
System.Diagnostics.Process https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process?view=netframework-4.5.2
我知道的最后一种方法是使用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()
}
}