Exception 一次简单的尝试/抓住并不能';行不通
这是我的代码,非常简单:Exception 一次简单的尝试/抓住并不能';行不通,exception,powershell,powershell-2.0,powershell-3.0,Exception,Powershell,Powershell 2.0,Powershell 3.0,这是我的代码,非常简单: $TargetFolder = 'M:\' try{ $Getfolderlist = Get-ChildItem $TargetFolder -Recurse | ? { $_.PSIsContainer -and $_.Name -eq 'old' } }catch { Write-Host "Error ! :) " } 它不工作,我得到一个powershell异常: Get-ChildItem : Cannot find drive. A d
$TargetFolder = 'M:\'
try{
$Getfolderlist = Get-ChildItem $TargetFolder -Recurse | ? { $_.PSIsContainer -and $_.Name -eq 'old' }
}catch {
Write-Host "Error ! :) "
}
它不工作,我得到一个powershell异常:
Get-ChildItem : Cannot find drive. A drive with the name 'M' does not exist.
At C:\ef-scripts\PurgeDeliveryZip\purge_delivery_zip.ps1:23 char:18
+ $Getfolderlist = Get-ChildItem $TargetFolder -Recurse | ? { $_.PSIsContainer -an ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (M:String) [Get-ChildItem], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
谢谢您的帮助。您需要-ErrorAction设置为Stop。这样,catch块就会得到异常。在此处阅读有关try-catch用法的信息: 此外,您可能还需要阅读有关在PowerShell中终止错误的信息以及公共参数帮助
$TargetFolder = 'M:\'
try{
$Getfolderlist = Get-ChildItem $TargetFolder -Recurse -Ea Stop | ? { $_.PSIsContainer -and $_.Name -eq 'old' }
}
catch {
Write-Host "Error ! :) "
}