Introduction

PowerShell provides powerful cmdlets to manage and automate tasks. One such cmdlet is Start-Process, which allows you to run executables from within a PowerShell script. You can also pass arguments, wait for the process to complete, and capture the exit code to handle the outcome appropriately.

Running an Executable

To run an executable from a PowerShell script, use the Start-Process cmdlet. Here’s an example of how to launch an installer with arguments:

Start-Process -FilePath "$CurrentPath\dotNetFx40_Full_x86_x64.exe" -ArgumentList "/q /norestart" -Wait

In this example:

  • -FilePath specifies the path to the executable.
  • -ArgumentList provides the arguments to pass to the executable.
  • -Wait ensures the script waits for the process to complete before continuing.

Capturing the Exit Code

To capture the exit code of the executable, use the -PassThru parameter with Start-Process and store the process object in a variable. Here’s how:

# Define the executable and arguments
$executablePath = "$CurrentPath\dotNetFx40_Full_x86_x64.exe"
$arguments = "/q /norestart"

# Start the process and wait for it to complete
$process = Start-Process -FilePath $executablePath -ArgumentList $arguments -PassThru -Wait

# Retrieve the exit code
$exitCode = $process.ExitCode

# Display the exit code
Write-Host "Exit Code: $exitCode"

This script launches the executable, waits for it to complete, and captures the exit code, which can be used for further processing or error handling.

Example Script

Here is a complete PowerShell script that runs an executable, waits for it to finish, and retrieves the exit code:

# Define the path to the executable and arguments
$CurrentPath = "C:\Path\To\Executable"
$executablePath = "$CurrentPath\dotNetFx40_Full_x86_x64.exe"
$arguments = "/q /norestart"

# Start the process and wait for it to complete
$process = Start-Process -FilePath $executablePath -ArgumentList $arguments -PassThru -Wait

# Retrieve the exit code
$exitCode = $process.ExitCode

# Output the exit code
Write-Host "Exit Code: $exitCode"

# Handle the exit code (optional)
if ($exitCode -eq 0) {
    Write-Host "The executable ran successfully."
} else {
    Write-Host "The executable encountered an error. Exit Code: $exitCode"
}

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.