24/7/365 Support

Determine the Status of the Last Windows PowerShell Command

Problem

You want to get status information about the last command you executed, such as whether it succeeded.

Solution

Use one of the two variables PowerShell provides to determine the status of the last command you executed: the $lastExitCode variable and the $? variable.

$lastExitCode

Anumber that represents the exit code/error level of the last script or application that exited

$? (pronounced “dollar hook”)

A Boolean value that represents the success or failure of the last command

Discussion

The $lastExitCode PowerShell variable is similar to the %errorlevel% variable in DOS. It holds the exit code of the last application to exit. This lets you continue to interact with traditional executables (such as ping, findstr, and choice) that use exit codes as a primary communication mechanism. PowerShell also extends the meaning of this variable to include the exit codes of scripts, which can set their status using the exit.

Example 17. Interacting with the $lastExitCode and $? variables

PS >ping localhost

Pinging MyComputer [127.0.0.1] with 32 bytes of data:

Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:

Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milliseconds:

Minimum = 0ms, Maximum = 0ms, Average = 0ms PS >$? True PS >$lastExitCode

Example 17. Interacting with the $lastExitCode and $? variables (continued)

0 PS >ping missinghost Ping request could not find host missinghost. Please check the name and try again. PS >$? False PS >$lastExitCode 1

The $? variable describes the exit status of the last application in a more general manner. PowerShell sets this variable to False on error conditions such as when:

  • An application exits with a nonzero exit code.
  • A cmdlet or script writes anything to its error stream.
  • A cmdlet or script encounters a terminating error or exception.

For commands that do not indicate an error condition, PowerShell sets the $? variable to True.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say