Error handling for native commands

by May 11, 2011

When you need to handle errors created by native commands, you can use a wrapper function like Call. It will automatically discover when a native command writes to the error stream and return a warning:

function Call {
  $command = $Args -join " "
  $command += " 2>&1"
  $result = Invoke-Expression($command)
  $result | 
    %{$e=""}{ if( $_.WriteErrorStream ) {$e += $_ } else {$_} }{Write-Warning $e}
}

call net use willi

 

 

Twitter This Tip!
ReTweet this Tip!