Powershell:生产调试/良好的异常处理 [英] Powershell: Debug in Production / Good Exception Handling

查看:40
本文介绍了Powershell:生产调试/良好的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在生产中分析 powershell cmdlet 的最佳方法是什么?假设您编写了一个执行以下操作的脚本 -

<块引用>

  1. 写入 lof 注册表值
  2. 注册 COM Dll
  3. 制作 IIS 应用程序池
  4. 启动 Windows 服务

&...中间出了点问题,那么通知用户以便可以跟踪和调试根问题的最佳做法是什么?

<块引用>

假设由于某种原因,用户凭据无法创建 AppPool我想在那个时候停止处理加上我想回滚我之前所做的.

详细模式 + 日志记录是在每一步收集每个细节的优雅方式吗?

解决方案

我写了一个 Write-Log 函数,我发布在 poshcode ( http://poshcode.org/3270 ),我用于生产级 PowerShell 程序.或者,您可以使用 Start-Transcript 将控制台上显示的几乎所有内容记录到文件中.关于 Start-Transcript -

有几个问题

  1. 它不会记录外部程序输出,除非您通过主机输出 API 强制它通过管道传输到 Out-Host,例如 ping.exe localhost |外主机.
  2. 并非所有主机都支持它.例如 PowerGUI 不支持它,因此您必须使用 $host 添加主机检查.

我通常用于错误处理的模式是将所有内容包装在 try/catch 中.异常对象将在 catch 块中作为 $_ 可用.它将包含有关发生的错误的所有信息、消息、行号和列号等...

我还将 $ErrorActionPreference 设置为 Stop 以便所有 cmdlet 都抛出终止错误,因此脚本不会继续.它看起来像这样:

$ErrorActionPreference = "停止"尝试 {# 写入 lof 的注册表值New-Item -Path HKCU:\Software\MyTest -ItemType 目录New-ItemProperty -Path HKCU:\Software\MyTest -Name MyTestValue -Value Test# 注册 COM Dllregsrv32 my.dllif ($LASTEXITCODE -ne 0) { throw "无法注册 my.dll" }# 制作 IIS 应用程序池IIS:\>New-WebAppPool NewAppPool# 启动 Windows 服务Start-Service -Name MyService} 抓住 {写日志(脚本失败.错误是:'{0}'."-f $_)}

回滚并不容易...唯一可能容易回滚的是注册表操作,因为注册表支持事务(假设 Vista 或更高版本).您可以创建一个事务(如数据库)并在发生错误时将其回滚.您提到的其余操作将需要特定代码来回滚它们.您可以像这样将回滚代码添加到 catch 块:

} catch {# 撤销注册事务.# 注销DLL.# 删除应用池(如果存在).# 停止windows服务.}

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 values
  2. Register COM Dlls
  3. Make IIS AppPools
  4. 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-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.
}

这篇关于Powershell:生产调试/良好的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆