如何"get"异常上下文以进行错误处理?



>我有一个运行良好的脚本,但我正在考虑通过添加我过去收到的更多异常处理来增强它,以防将来的用户遇到困难并需要明确的提示可能的解决方法来解决问题如果以后发生。

我本质上想做的是,一旦我尝试运行脚本,我就得到了未经授权访问以运行脚本的执行策略异常。

我不想将异常吐到日志文件中,然后我可以在其中获取某些字符串的内容以打印可能的解决方案。

相反,我想立即从控制台获取异常字符串的一部分,然后暗示解决方案可能是什么。

有这样的选择吗?

我将在这里使用File.WriteAllLines方法作为我的示例。 如果您的目标是使用单个 catch 语句,则可以对异常消息使用开关:

$ErrorActionPreference = 'Stop'
try
{
[System.IO.File]::WriteAllLines('C:Temptest.txt', 'Test message')
}
catch
{
switch -Regex ($PSItem.Exception.Message)
{
'null'
{
'null path passed!'
}
'invalid'
{
'bad path passed!'
}
default
{
'didn''t catch this case!'
}
}
}

但是,这种方式不是很易于维护。 更好的方法是捕获不同的异常:

$ErrorActionPreference = 'Stop'
try
{
[System.IO.File]::WriteAllLines('C:Temptest.txt', 'Test message')
}
catch [System.ArgumentNullException]
{
'null path passed!'
}
catch [System.IO.DirectoryNotFoundException]
{
'bad path passed!'
}
catch
{
'didn''t handle this case!'
}

对于运行脚本的异常情况:

try
{
& 'C:myscript.ps1'
}
catch [System.Management.Automation.PSSecurityException]
{
"Execution policy bad! $PSItem"
}
catch
{
"This exception was thrown by something in the script and not caught: $PSItem"
}

您可以在Powershell中使用Try Catch方法。结合开关,您可以整理出要显示的消息。

try{
sdasdasdad
}catch [System.Exception]{
switch ($_.Exception.GetType().FullName){
"System.Management.Automation.CommandNotFoundException"{
"No Command Found. Please try a diffrent command."
}
default { 
$_.Exception.message
}
}
}

最新更新