Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the error code when there is error in powershell?

Tags:

powershell

My snippet is something like this:

$msg=Remove-Item -Recurse -Force C:\users\bkp  2>&1
if ($LASTEXITCODE -eq 1)
{
  "Encountered error during Deleting the Folder. Error Message is $msg. Please check." >> $LogFile
  exit
 }

The folder C:\users\bkp does not exist. Even though $msg gives me the error message $LASTEXITCODE is still 0. How do I capture as a flag?

like image 288
Avinash Ganesh Avatar asked Jul 04 '13 02:07

Avinash Ganesh


People also ask

How do I get an error code in PowerShell?

Use the try block to define a section of a script in which you want PowerShell to monitor for errors. When an error occurs within the try block, the error is first saved to the $Error automatic variable. PowerShell then searches for a catch block to handle the error.

What does $_ mean in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

How do I force an error in PowerShell?

The throw keyword causes a terminating error. You can use the throw keyword to stop the processing of a command, function, or script. For example, you can use the throw keyword in the script block of an if statement to respond to a condition or in the catch block of a try - catch - finally statement.

Which cmdlet can be used to find error in the script?

Use the Command's -ErrorAction Parameter Cmdlet's and functions/scripts/modules that use [cmdletbinding()] enable utilization of the -ErrorAction common parameter. This parameter allows you to specify different actions to take when an error is encountered. Display error, and stop execution.


2 Answers

You can use the $? automatic variable to determine the result of the last command. If you need access to the actual error, you can use the $Error automatic variable. The first item in the array is the last error thrown:

Remove-Item -Recurse -Force C:\users\bkp 2>&1
if( -not $? )
{
    $msg = $Error[0].Exception.Message
    "Encountered error during Deleting the Folder. Error Message is $msg. Please check." >> $LogFile
    exit
}
like image 114
Aaron Jensen Avatar answered Oct 02 '22 14:10

Aaron Jensen


$LASTEXITCODE is strictly for command line programs to return their status. Cmdlets that are built into PS, such as Remove-item return their errors in up to 3 ways. For warnings, they write messages (or other .NET objects) to the "warning stream". In PSv3 there is a straightforward way to redirect that stream to a file: cmdlet blah blah blah 3>warning.out. The second is via the error stream. That stream can be redirected as well ... 2>error.out, or more typically errors are caught with try/catch or trap, or written to a variable with the -ErrorVariable parameter (see help about_commonparameters). The third way is for errors to be "thrown". Unless caught (try/catch or trap), a thrown error will cause the script to terminate. Thrown errors generally are subclasses of the .NET class system.Management.Automation.ErrorRecord. An ErrorRecord provides a lot more information about an error than a return code.

If remove-item fails due to a file not found error, it writes a System.Management.Automation.ItemNotFoundException to the error stream. Using a try/catch you can filter for that specific error or other specific errors from remove-item. If you are just typing in PS commands from the command line you can enter $error[0]|select-object * to get a lot of info on the last error.


You could do this:

try {
  Remove-Item -Recurse -Force C:\users\bkp  2>&1
} catch {
  # oops remove-item failed. Write warning then quit 
  # replace the following with what you want to do
  write-warning "Remove-item encounter error: $_"
  return # script failed
}
like image 45
Χpẘ Avatar answered Oct 02 '22 13:10

Χpẘ