🎓 A1Learner
🔍
0 of 47 lessons completed

PowerShell Error Records

An error record is a bundle of facts about one error. Inside a catch block, $_ holds the current error record.

Read the message

A failing Get-Item command inside try gives catch a record to read. Print its message first.

try { Get-Item "/definitely-not-here-xyz" -ErrorAction Stop } catch { "Message: " + $_.Exception.Message }

Read the category

The category names the broad kind of error. A missing path is a missing object.

try { Get-Item "/definitely-not-here-xyz" -ErrorAction Stop } catch { "Category: " + $_.CategoryInfo.Category }

Read the error id

The error id is a fixed name for the error. It does not change between runs.

try { Get-Item "/definitely-not-here-xyz" -ErrorAction Stop } catch { "Error id: " + $_.FullyQualifiedErrorId }

Example

try {
  Get-Item "/definitely-not-here-xyz" -ErrorAction Stop
} catch {
  "Message: " + $_.Exception.Message
  "Category: " + $_.CategoryInfo.Category
  "Error id: " + $_.FullyQualifiedErrorId
}

Key points

  • Error record: one error saved as a bundle of named facts.
  • Exception message: the plain-words reason the command failed.
  • Category: the broad kind of the error, shown as ObjectNotFound for a missing path.
  • Fully qualified error id: the fixed name of the error, which stays the same each run.
  • Catch block: the place where you read the error record safely.

In this example, try runs a Get-Item command for a missing path, catch runs when it stops, and catch prints the message, the category, and the error id in order.

Note

Print one property at a time, never the whole record, so the output stays stable.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does $_.CategoryInfo.Category print for a missing path?