一、利用环境变量

PowerShell中定义了两个变量进行默认的错误处理,输入“Get-Variable”得到Powershell系统中所有预定义的变量;

Error:这个变量会储存整个脚本所有的错误信息;

ErrorActionPreference: 这个变量定义powershell出错后,整个脚本该如何处理,预定义为“Continue”;

ErrorActionPreference包括SilentlyContinue, Continue, Stop, 和Inquire四个参数;

PowerShell简单的错误处理机制_PowerShell 

例如我们用“Get-Process –FileVersionInfo”命令来测试看看ErrorActionPreference变量的含义;

(1)默认情况下ErrorActionPreference为“Continue”;

脚本出错后仍在继续的执行:

PowerShell简单的错误处理机制_PowerShell_02

error变量储存了错误的内容:

PowerShell简单的错误处理机制_简单的错误处理机制_03


(2)设置ErrorActionPreference为“stop”;

脚本遇到错误便停止;

PowerShell简单的错误处理机制_简单的错误处理机制_04

(3)设置ErrorActionPreference为“Inquire”;

脚本遇到错误需要人为的干预;

PowerShell简单的错误处理机制_简单的错误处理机制_05

(4)设置ErrorActionPreference为“SilentlyContinue”;

脚本遇到错误后隐藏错误继续执行,错误信息写入Error变量;

PowerShell简单的错误处理机制_简单的错误处理机制_06

不管ErrorActionPreference的值设为那一个,error变量都保存着错误信息;



二、利用“-ErrorAction”参数指定

ErrorAction包括SilentlyContinue, Continue, Stop, Inquire,Suspend和Ignore六个参数;

例如我们用“Get-Process –FileVersionInfo”命令来测试

(1)默认情况下-ErrorAction为“Continue”;

脚本出错后仍在继续的执行:

PowerShell简单的错误处理机制_PowerShell_07

(2)默认情况下-ErrorAction为“Stop”;

脚本出错后停止的执行:

PowerShell简单的错误处理机制_简单的错误处理机制_08

(3)设置-ErrorAction为“Inquire”;

脚本遇到错误需要人为的干预;

PowerShell简单的错误处理机制_PowerShell_09

(4)设置-ErrorAction为“Ignore”;

脚本遇到错误后忽略错误继续执行,错误信息不写入Error变量;

PowerShell简单的错误处理机制_PowerShell_10

(5)设置-ErrorAction为“SilentlyContinue”;

脚本遇到错误后隐藏错误继续执行,错误信息写入Error变量;

PowerShell简单的错误处理机制_简单的错误处理机制_11

(6)设置-ErrorAction为“Suspend”;

This value is only available in Windows PowerShell workflows. 
When a workflow runs into terminating error, this action preference automatically suspends the job to allow for further investigation. Afterinvestigation, the workflow can be resumed.