Powershell Script to run exe file with parameters

Issue

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

Solution

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

Answered By – Maximilian Burszley

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published