7

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

4
  • I would use Start-Process but your example works as well. Commented Nov 14, 2018 at 15:09
  • 2
    You don't need " around $Command. Commented Nov 14, 2018 at 16:47
  • 1
    @Bill_Stewart "$($Command.ToString())" :P Commented Nov 14, 2018 at 17:33
  • @TheIncorrigible1 :-) Commented Nov 14, 2018 at 18:09

1 Answer 1

13

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()
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.