How to enhance script using Exception and Error Handling?
One of my client came up with huge requirement in PowerShell, they got some issue while executing the script and need to know how to enhance the script with error handling.
Nothing much I could say than the below :)
help about_Try_Catch_Finally
or try
Get-Help Start-Transcript -Detailed
Use as required.
Demo using Try Catch and Finally :) My All time favorite.
try
{
Get-WmiObject -Class Win32_ComputerSystem -ComputerName Not-Online -ErrorAction Stop
}
Catch{
$Ex = $($_.Exception.GetType().FullName)
$ErrMessage = $($_.Exception.Message)
$date = get-Date
}
finally{
Add-Content -Value "$date
$EX , $ErrMessage" -Path C:\Temp\Logs.txt
Invoke-Item C:\Temp\Logs.txt
}
Error Log appears like below
04/07/2014 15:10:32
System.Runtime.InteropServices.COMException , The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
Enjoy PowerShell!!!