Powershell Script to run exe file with parameters

百般思念 提交于 2019-12-24 08:37:49

问题


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

thanks


回答1:


You have a couple options when running an external executable.


Splatting

$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.


Call the executable with arguments at once

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

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

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


来源:https://stackoverflow.com/questions/53303222/powershell-script-to-run-exe-file-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!