Supress Powershell中的错误并显示自定义错误消息

时间:2019-02-20 09:56:00

标签: powershell

我创建了一个PowerShell脚本,该脚本将为Cisco Meraki添加VPN连接。 该脚本本身可以正常运行,但是如果发生错误,则会显示“已完成”弹出窗口,并在PS窗口中显示错误消息。

是否可以阻止错误并根据出现的错误显示自定义错误弹出窗口,同时阻止“已完成”弹出窗口的显示?

我知道$ErrorActionPreference= 'silentlycontinue',但不确定如何通过自定义错误来实现。

  

为Cisco Meraki添加VPN连接的脚本。

$Name = Read-Host -Prompt 'Enter the profile name for this VPN connection'
$password = Read-Host -assecurestring "Please enter your Pre-shared Key"
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
Add-VpnConnection -Name "$Name" -ServerAddress 193.214.153.2 -AuthenticationMethod MSChapv2 -L2tpPsk "$password" -TunnelType L2tp -RememberCredential -Force
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("VPN-profile for $Name has been created.
You may now use this connection.
Username and password is required on first time sign on.
Support: _witheld_ | _witheld_",0,"Completed")

2 个答案:

答案 0 :(得分:4)

由于错误发生后脚本继续运行,因此您正在处理非终止错误 ,因此您可以使用
-ErrorVariable common parameter捕获给定cmdlet调用的错误

使用一个简化的示例,您可以类似地将其应用于Add-VpnConnection调用:

 # Call Get-Item with a nonexistent path, which causes a *non-terminating* error. 
 # * Capture the error with -ErrorVariable in variable $err.
 # * Suppress the error console output with -ErrorAction SilentlyContinue
 Get-Item /NoSuch/Path -ErrorVariable err -ErrorAction SilentlyContinue

 $null = (New-Object -ComObject Wscript.Shell).Popup(
    $(if ($err) { "Error: $err" } else { 'Success.' })
 )

如果您遇到的是 终止错误,则必须使用try / catch

 # Call Get-Item with an unsupported parameter, which causes a 
 # *(statement-)terminating* error. 
 try {
   Get-Item -NoSuchParam
 } catch {
   # Save the error, which is a [System.Management.Automation.ErrorRecord]
   # instance. To save just a the *message* (a string), use 
   # err = "$_"
   $err = $_ 
 }

 $null = (New-Object -ComObject Wscript.Shell).Popup(
    $(if ($err) { "Error: $err" } else { 'Success.' })
 )

注意:

  • -ErrorAction-ErrorVariable都无法解决终止错误。
  • 相反,try / catch无法用于处理非终止错误,这可能是Ranadip Dutta's answer对您不起作用的原因。< / li>

有关PowerShell错误处理的详细讨论,请参见this GitHub issue

答案 1 :(得分:1)

您必须对脚本进行错误处理。我在下面的脚本中给出了它的整体信息,但是您可以根据需要进行配置:

try
{
$Name = Read-Host -Prompt 'Enter the profile name for this VPN connection'
$password = Read-Host -assecurestring "Please enter your Pre-shared Key"
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
Add-VpnConnection -Name "$Name" -ServerAddress 193.214.153.2 -AuthenticationMethod MSChapv2 -L2tpPsk "$password" -TunnelType L2tp -RememberCredential -Force
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("VPN-profile for $Name has been created.You may now use this connection.Username and password is required on first time sign on.Support: _witheld_ | _witheld_",0,"Completed")
}
catch
{
"Your custom message"
$_.Exception.Message
}

要进一步参考,请阅读TRY/CATCH/FINALLY in Powershell

希望有帮助。