【问题标题】:Powershell Script to run exe file with parameters使用参数运行 exe 文件的 Powershell 脚本
【发布时间】:2019-04-17 14:20:40
【问题描述】:

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

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

谢谢

【问题讨论】:

  • 我会使用Start-Process,但您的示例也适用。
  • $Command 周围不需要"
  • @Bill_Stewart "$($Command.ToString())":P
  • @TheIncorrigible1 :-)

标签: windows powershell scripting exe


【解决方案1】:

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


Splatting

$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

Start-Process

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

$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 类。如果我需要对流程进行更多控制,例如收集其输出,我会使用此方法:

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()
    }
}

【讨论】:

    猜你喜欢
    • 2011-06-06
    • 2017-11-17
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多