且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-02 19:35:40

在运行外部可执行文件时,您有两个选择.

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