使用参数运行exe文件的Powershell脚本 [英] Powershell Script to run exe file with parameters
问题描述
我需要脚本来运行带参数的exe文件. 那是我写的,如果有更好的方法可以做到呢?
I need script to run exe file with parameters. That's what I wrote, if there's a better way to do it?
$Command = "\\Networkpath\Restart.exe"
$Parms = "/t:21600 /m:360 /r /f"
$Prms = $Parms.Split(" ")
& "$Command" $Prms
谢谢
推荐答案
在运行外部可执行文件时,您有两个选择.
You have a couple options when running an external executable.
$command = '\\netpath\restart.exe'
$params = '/t:21600', '/m:360', '/r', '/f'
& $command @params
此方法实际上将把数组作为可执行文件的参数加入.这样可以使您的参数列表更加简洁,并可以将其重写为:
This method will essentially join your array as arguments to the executable. This allows your list of arguments to be cleaner and can be re-written as:
$params = @(
'/t:21600'
'/m:360'
'/r'
'/f'
)
通常,这是我最喜欢的解决问题的方法.
This is usually my favorite way to address the problem.
You don't necessarily need to have variables or even the call operator (&
) if you don't have spaces in arguments, path, etc.
\\netpath\restart.exe /t:21600 /m:360 /r /f
Start-Process
这是我的第二个建议,因为它使我可以更好地控制最终过程.有时可执行文件会生成子流程,并且您的调用运算符不会在脚本继续进行之前等待该流程结束.这种方法使您可以控制它.
Start-Process
This is my second go-to because it gives me more control over the eventual process. Sometimes executables spawn sub-processes and your call operator won't wait for the process to end before moving on in your script. This method gives you control over that.
$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
我所知道的最后一种方法,直接使用Process
.NET类.如果需要对过程进行更多控制,例如收集其输出,则可以使用此方法:
System.Diagnostics.Process
Last of the methods I know, using the Process
.NET class directly. I use this method if I need even more control of the process, such as collecting its output:
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()
}
}
这篇关于使用参数运行exe文件的Powershell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!