1

Currently I start processes in PowerShell like this:

$proc = Start-Process notepad -Passthru
$proc | Export-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')

to later on kill it like this:

$proc = Import-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
$proc | Stop-Process

The problem is that if the process died before I got to call $proc | Stop-Process, I will get error in the PowerShell output. I need to disable this error and just get the Boolean value indicating if Stop-Process was successfully into a PowerShell script's variable. How can I get this info in PS?

Maxim V. Pavlov
  • 10,303
  • 17
  • 74
  • 174

1 Answers1

3

Use the $? variable to determine the success or failure of your last executed command. Set $ErrorActionPreference variable to decide how error output is handled per script, or use -ErrorAction parameter to set it per command:

$proc = Import-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
$proc | Stop-Process -ErrorAction SilentlyContinue
if($?) {
    #Success
    Write-host $proc " Stopped Successfully"
}
else {
    #Failure
    #Use $error variable to retrieve the message
    Write-Error $error[0]
}
Cole9350
  • 5,444
  • 2
  • 34
  • 50