使用PowerShell脚本运行带参数的exe文件

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

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

谢谢


我会使用 Start-Process,但你的示例也可以工作。 - TobyU
1
你不需要在 $Command 周围加上 " - Bill_Stewart
1
@Bill_Stewart "$($Command.ToString())" :PPS: 该语句为代码中的一条输出语句。 - Maximilian Burszley
@TheIncorrigible1 :-) - Bill_Stewart
1个回答

13

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


Splatting

Splatting是一种将参数作为哈希表传递给命令的技术。这使得代码更加易于阅读和维护。

$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

这是我第二选择的方法,因为它可以更好地控制最终进程。有时可执行文件会生成子进程,而调用运算符在脚本中继续执行之前不会等待进程结束。这种方法可以让您对此进行控制。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接