这是我的代码,非常简单:
$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
感谢您的帮助。
答案 0 :(得分:7)
您需要将-ErrorAction设置为Stop。这样catch块就会获得异常。在这里阅读try catch usage:http://technet.microsoft.com/en-us/library/hh847793.aspx
此外,您可能希望阅读有关终止PowerShell中的错误和ErrorAction常见参数帮助的信息。
$TargetFolder = 'M:\'
try{
$Getfolderlist = Get-ChildItem $TargetFolder -Recurse -Ea Stop | ? { $_.PSIsContainer -and $_.Name -eq 'old' }
}
catch {
Write-Host "Error ! :) "
}