我有一个运行得很好的脚本,但是我正在考虑通过添加更多我过去收到的异常处理来增强它,以防将来的用户苦苦挣扎,并且需要明确的提示来解决可能出现的问题的解决方案一段时间之后。
我本质上想做的就是说,一旦我尝试运行脚本,就会得到执行策略异常,该异常是未经授权的运行脚本。
我不想将异常吐到日志文件中,然后我可以在其中获取某些字符串的内容以打印可能的解决方案。
相反,我想立即从控制台获取异常字符串的一部分,然后提示解决方案。
有这样的选择吗?
答案 0 :(得分:3)
在这里,我将使用File.WriteAllLines
方法作为示例。如果您的目标是只有一个catch语句,则可以在异常消息上使用一个开关:
$ErrorActionPreference = 'Stop'
try
{
[System.IO.File]::WriteAllLines('C:\Temp\test.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:\Temp\test.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"
}
答案 1 :(得分:2)
您可以在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
}
}
}