Powershell: Debug in Production / Good Exception Handling

前端 未结 2 999
不思量自难忘°
不思量自难忘° 2021-01-15 22:06

What is the best way to analyze powershell cmdlets in production ? Suppose you write a script which does the following -

  1. Write lof of registry
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-15 22:19

    I wrote a Write-Log function that I posted on poshcode ( http://poshcode.org/3270 ) that I use for production level PowerShell programs. Alternatively you could use Start-Transcript which logs almost everything displayed on the console to a file. There are a couple gotchas about Start-Transcript -

    1. It won't log external program output unless you force it through the host output API by piping it to Out-Host such as ping.exe localhost | Out-Host.
    2. It's not supported on all hosts. For example PowerGUI doesn't support it so you have to add a host check using $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 $ErrorActionPreference to Stop so that all cmdlets throw a terminating error so the script won't continue. It looks like this:

    $ErrorActionPreference = "Stop"
    try {
        # Write lof of registry values
        New-Item -Path HKCU:\Software\MyTest -ItemType Directory
        New-ItemProperty -Path HKCU:\Software\MyTest -Name MyTestValue -Value Test
    
        # Register COM Dlls
        regsrv32 my.dll
        if ($LASTEXITCODE -ne 0) { throw "Failed to register my.dll" }
    
        # Make IIS AppPools
        IIS:\>New-WebAppPool NewAppPool
    
        # Start Windows Services
        Start-Service -Name MyService
    } catch {
        Write-Log ("Script failed. The error was: '{0}'." -f $_)
    }
    

    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:

    } catch {
        # Undo the registry transaction.
        # Unregister the DLL.
        # Delete the App pool if it exists.
        # Stop the windows service.
    }
    

提交回复
热议问题