2

这是我的代码,非常简单:

$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

谢谢你的帮助。

4

1 回答 1

7

您需要将 -ErrorAction 设置为 Stop。这样,catch 块就会获得异常。在此处阅读有关 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 ! :) "    
}
于 2013-08-06T13:17:23.943 回答