Powershell脚本运行带有参数的exe文件

Men*_*eni 3 windows powershell scripting exe

我需要脚本来运行带参数的 exe 文件。这就是我写的,如果有更好的方法吗?

$Command = "\\Networkpath\Restart.exe"
$Parms = "/t:21600 /m:360 /r /f"
$Prms = $Parms.Split(" ")
& "$Command" $Prms
Run Code Online (Sandbox Code Playgroud)

谢谢

The*_*le1 5

运行外部可执行文件时,您有几个选项。


飞溅

$command = '\\netpath\restart.exe'
$params = '/t:21600', '/m:360', '/r', '/f'
& $command @params
Run Code Online (Sandbox Code Playgroud)

此方法本质上将加入您的数组作为可执行文件的参数。这使您的参数列表更清晰,并且可以重写为:

$params = @(
    '/t:21600'
    '/m:360'
    '/r'
    '/f'
)
Run Code Online (Sandbox Code Playgroud)

这通常是我最喜欢的解决问题的方式。


立即使用参数调用可执行文件

如果参数、路径等中没有空格,则不一定需要变量甚至调用运算符 ( &)

\\netpath\restart.exe /t:21600 /m:360 /r /f
Run Code Online (Sandbox Code Playgroud)

Start-Process

这是我的第二个目标,因为它让我可以更好地控制最终过程。有时可执行文件会产生子进程,并且您的呼叫操作员不会等待进程结束,然后再继续执行您的脚本。这种方法使您可以控制它。

$startParams = @{
    'FilePath'     = '\\netpath\restart.exe'
    'ArgumentList' = '/t:21600', '/m:360', '/r', '/f'
    'Wait'         = $true
    'PassThru'     = $true
}
$proc = Start-Process @startParams
$proc.ExitCode
Run Code Online (Sandbox Code Playgroud)

System.Diagnostics.Process

我知道的最后一个方法,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()
    }
}
Run Code Online (Sandbox Code Playgroud)