What is the best way to analyze powershell cmdlets in production ? Suppose you write a script which does the following –
- Write lof of registry values
- Register COM Dlls
- Make IIS AppPools
- Start Windows Services
&…something goes wrong in between, then what are the best practices to inform user such that root issue can be traced and debugged ?
Suppose, user credentials fail for AppPool creation for some reason
and I want to stop processing at that time plus I want to rollback
what I had done earlier.
Is verbose mode + Logging an elegant way to collect each details at every step ?
I wrote a
Write-Logfunction that I posted on poshcode ( http://poshcode.org/3270 ) that I use for production level PowerShell programs. Alternatively you could useStart-Transcriptwhich logs almost everything displayed on the console to a file. There are a couple gotchas aboutStart-Transcript–Out-Hostsuch asping.exe localhost | Out-Host.$host.The pattern I usually use for error handling is to wrap everything in a try/catch. The exception object will be available as
$_in the catch block. It will contain everything about the error that happened, the message, the line and column number etc…I also set the
$ErrorActionPreferencetoStopso that all cmdlets throw a terminating error so the script won’t continue. It looks like this:Rolling back is not easy… The only thing that might be easy to roll back are the registry operations because the registry supports transactions (assuming Vista or beyond). You can just create a transaction (like a database) and roll it back if an error occurs. The rest of the operations you mentioned will need specific code to roll them back. You could add the rollback code to the catch block like this: