gpt4 book ai didi

powershell - 无法从 Get-PSDrive 捕获 DriveNotFoundException

转载 作者:行者123 更新时间:2023-12-03 14:21:47 24 4
gpt4 key购买 nike

我无法 catch DriveNotFoundExceptionGet-PSDrive 生成在以下示例中:

try {
# Assumes no Q:\ drive connected.
$foo = Get-PSDrive -name 'Q' -ErrorAction Stop
}
catch [System.Management.Automation.DriveNotFoundException] {
Write-Output "Drive not found."
}
catch {
Write-Output "Something else went wrong."
}

这应该打印以下内容:
PS C:\temp> .\foo.ps1
Drive not found.
PS C:\temp>

相反,我得到:
PS C:\temp> .\foo.ps1
Something else went wrong.
PS C:\temp>

如果相关,我正在使用 Powershell 2.0。

最佳答案

问题是因为 -ErrorAction Stop正在更改 try/catch 块看到的异常类型。

您可以通过捕获 ActionPreferenceStopException 来证明这一点。类型。所以让我们运行一些故障排除代码来看看发生了什么:

try {
# Assumes no Q:\ drive connected.
$foo = Get-PSDrive -name 'Q' -ErrorAction Stop
}
catch [System.Management.Automation.DriveNotFoundException] {
Write-Output "Drive not found."
}
catch [System.Management.Automation.ActionPreferenceStopException] {
Write-Output "Stop Exception."
write-host "Caught an exception:" -ForegroundColor Red
write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
}
catch
{
write-host "Caught an exception:" -ForegroundColor Red
write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
}

这将返回以下输出:
Stop Exception.
Caught an exception:
Exception Type: System.Management.Automation.DriveNotFoundException
Exception Message: Cannot find drive. A drive with the name 'Q' does not exist.

所以你看到 try/catch 捕获了 [System.Management.Automation.ActionPreferenceStopException]异常(exception), 即使 异常类型是 [System.Management.Automation.DriveNotFoundException]在 catch 块内。

所以,我们可以用@haliphax 的解决方案稍加修改的版本来处理它,即检查 ActionPreferenceStopException 内部的错误类型。捕获块:
try {
# Assumes no Q:\ drive connected.
$foo = Get-PSDrive -name 'Q' -ErrorAction Stop
}
catch [System.Management.Automation.ActionPreferenceStopException] {
if ($Error[0].Exception.GetType().Name -eq 'DriveNotFoundException') {
Write-Output "Drive not found."
}
else {
Write-Output "Something else went wrong."
}
}
catch {
Write-Output "Something else went wrong."
}

关于powershell - 无法从 Get-PSDrive 捕获 DriveNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35610660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com