我试图测量核心服务器上的下载目录,这些目录是来自用户的文件夹重定向,还有一些其他没有下载目录的目录。
因此尝试捕获此异常,但它既不捕获指定的异常,也不捕获所有的异常。
$path = "\\Server\folderredirection"
$childitem = Get-ChildItem -Path $path
foreach ($c in $childitem)
{
$dloads = "$path\$c\Downloads\*"
Write-Log "------------------------------------------"
try{
$files = Get-ChildItem -path $dloads -Recurse
$Size = ($files | Measure-Object -Sum Length).Sum / 1MB
$Size = [math]::Round($Size,2)
if($Size -gt 0)
{
Write-Log "$c has worth $Size MB items in downloads"
}else{
Write-Log "$c has no items in downloads"
}
$totalSize = $totalSize + $Size
}catch [System.Management.Automation.ItemNotFoundException]{
Write-Log "$c has no download dir"
}catch{
Write-Log "Unexpected Error while $c"
}
Write-Log "------------------------------------------"
}
我不知道我在PW中执行任务时是否失败还是欺骗自己。
谢谢您的帮助。
答案 0 :(得分:1)
为了使Catch块在Try..Catch中触发,必须抛出终止错误。 Get-ChildItem
默认为不存在的路径引发一个非终止错误。通过使用-ErrorAction
开关并将其设置为Stop
,可以强制cmdlet为所有错误抛出终止错误。或者,您可以更改全局$ErrorActionPreference
变量。
这应该有效:
$path = "\\Server\folderredirection"
$childitem = Get-ChildItem -Path $path
foreach ($c in $childitem)
{
$dloads = "$path\$c\Downloads\*"
Write-Log "------------------------------------------"
try{
$files = Get-ChildItem -path $dloads -Recurse -ErrorAction Stop
$Size = ($files | Measure-Object -Sum Length).Sum / 1MB
$Size = [math]::Round($Size,2)
if($Size -gt 0)
{
Write-Log "$c has worth $Size MB items in downloads"
}else{
Write-Log "$c has no items in downloads"
}
$totalSize = $totalSize + $Size
}catch [System.Management.Automation.ItemNotFoundException]{
Write-Log "$c has no download dir"
}catch{
Write-Log "Unexpected Error while $c"
}
Write-Log "------------------------------------------"
}