PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

image rotation

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.

Latest Scripts

12-18-2014 - users
12-16-2014 - Get-RegistryTimestamp
12-15-2014 - Get-ComPath

Latest Announcements/Events

10-31-2014 - Using PowerShell to download Teched Europe 2014 content
10-15-2014 - Class Dismissed
10-12-2014 - The Case for PowerShell

As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Catching Errors in Native EXEs (Part 2)

All versions

Here is yet another approach that you can use to detect errors emitted by console applications:

$ErrorActionPreference = 'Continue'
$result = net.exe user UserDoesNotExist 2>&1 

# $? is $false when something went wrong
if ($? -eq $false) {
    # read last error:
    $errMsg = $result.Exception.Message -join ','
    Write-Host "Something went wrong: $errMsg"
} else {
    Write-Host 'All is fine.'
} 

Note the use of $ErrorActionPreference: when it is set to 'Stop', the error would be converted into a .NET exception. The default setting for $ErrorActionPreference is 'Continue'. With this setting, the script can receive the error in $err.

The built-in variable $? Returns $false if the last call fails. In this case, the code returns an error message (or could do other things, like adding information to a log file).

Twitter This Tip! ReTweet this Tip!

Copyright 2012 PowerShell.com. All rights reserved.