这是我的代码,非常简单:
$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 block 就得到了异常。在这里阅读有关 try catch 用法的信息: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 ! :) "
}
关于exception - 简单的 Try/catch 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18081117/