Powershell尝试/捕获/最终没有正确执行(或者我完全没收它)

时间:2017-07-11 15:53:27

标签: powershell

我有一个检查循环组的脚本 该脚本获取域中的所有组(父组),检查这些组的成员资格,并添加具有' group'的objectClass的任何成员。到一个数组(子组)。

该脚本然后检查子组以查看父组是否是该组的成员(是的,它是允许的但仍然不是一个好主意)。

我添加了一个try / catch / finally块,因此我可以获取实际的组名,而不是PowerShell返回的截断错误消息。

问题是,脚本在遇到的第一个错误时停止,而不是继续。

这是我第一次尝试/抓住,所以请耐心等待。

这是脚本:

$original_ErrorActionPreference = 'Continue'
$ErrorActionPreference = 'Stop'

Import-Module -Name ActiveDirectory

$domains = @('corp.com', 'dom1.corp.com', 'dom2.corp.com')


foreach($domain in $domains){
  Write-Host $domain -ForegroundColor Yellow
  $parents = Get-ADGroup -server $domain -Properties name,objectclass -Filter * #get all domain groups
  write-host $parents.count

  $table = @()
  $pGroupCount = @($parents).Count

  $record = @{
    'Parent' = ''
    'Child' = ''
    'Nester' = ''
  }

  foreach($parent in $parents){ 
    Write-Host $parent.name -ForegroundColor Green

这个脚本到目前为止一直在努力。

这是失败的部分 -

    try { #get members in the parent that are groups
      $children = Get-ADGroupMember -Identity $parent | Where-Object{$_.ObjectClass -eq 'group'} | Select-Object name,distinguishedName,objectClass  
      } catch [Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember]{

        Write-Host $parent.name ' must be checked manually' -ForegroundColor blue -BackgroundColor Yellow
        $parent.distinguishedName | Out-String -Width 4096 | Out-File -FilePath "$env:USERPROFILE\desktop\$domain-manualCheck.txt" -Width 5120 -Append

    } finally {

    $pGroupCount = $pGroupCount - 1
    write-host $children.count ' - ' $children.name -ForegroundColor Gray
    Write-Host $pGroupCount ' groups to go' -foregroundColor yellow



  foreach($child in $children){ #get members in the children that are groups AND that have the same name as the parent
    $nested = Get-ADGroupMember $child.name | Where-Object {$_.objectClass -eq 'group' -and $_.name -eq $parent.name} 
    $nestedCount = @($nested).count

      if ($nestedCount -gt 0){
        foreach($nester in $nested){
          Write-Host $parent.name -ForegroundColor White
          Write-Host $nestedCount -ForegroundColor Magenta
          Write-Host $nester.name -ForegroundColor Cyan
          $record.'Parent' = $parent.name
          $record.'Child' = $child.name
          $record.'Nester' = $nester.name
          $objRecord = New-Object psobject -Property $record
          $table += $objRecord
        }
      }
    }
    $table | Export-Csv -Path "$env:USERPROFILE\desktop\$domain-Group-Report.csv" -NoTypeInformation
    $error | out-string -width 4096 | Out-File -FilePath "$env:USERPROFILE\desktop\$domain-Errors.txt" -Width 5120 -Append
  }
  }
  }
  $ErrorActionPreference = $original_ErrorActionPreference 

只要脚本遇到有问题的第一个组,就会返回错误(#comments已添加):

PS C:\Users\admin_j\Desktop> .\gtest.ps1
corp.com #current domain
283 #total group count
Exchange Servers #current group
6  -  Exchange Install Domain Servers Exchange Install Domain Servers Exchange Install Domain Servers Exchange Install Domain Servers Exchange Install Domain Servers #6 groups within the parent, groups are from sub-domains
Exchange Install Domain Servers
282  groups to go
Get-ADGroupMember : Cannot find an object with identity: 'Exchange Install Domain Servers' under: 'DC=corp,DC=com'.
At C:\Users\admin_j\Desktop\gtest.ps1:46 char:15
+     $nested = Get-ADGroupMember $child.name | Where-Object $_.objectClass -eq ' ...
+               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Exchange Install Domain Servers:ADGroup) [Get-ADGroupMember], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Cannot find an object with identity: 'Exchange Install Domain Servers' under: 'DC=corp,DC=com'.,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember

为什么,而不是将错误组(在这种情况下' Exchange安装域服务器' DC = corp,DC = com'。)写入文件,而不是脚本停止?该组确实存在。

我是否应该添加另一个块以捕获未找到的任何对象'错误并将其发送到文件?

谢谢!

1 个答案:

答案 0 :(得分:3)

作为Will's comment implies,你确实已经通过指定一个类型文字来填充你的catch子句,这个类型文字与你曾经期望抛出的异常相匹配。

catch子句的一般语法如下

catch [catch-type-list] <statement block>

其中[catch-type-list]是一个可选的异常类型列表,关联的语句块将作为异常处理程序。

这意味着,这个catch子句:

catch [Microsoft.ActiveDirectory.Management.Commands.GetADGroupMem‌​ber] {
    # ...
}

只会处理由类型[Microsoft.ActiveDirectory.Management.Commands.GetADGroupMem‌​ber]的异常引起的错误 - 这当然不是异常类型,因此关联的语句块永远不会执行。

为了使catch子句在此上下文中有意义,请指定相关的异常类型:

try{
    Get-ADGroupMember -Identity $parent
}
catch [Microsoft.ActiveDirectory.Management.ADServerDownException]{
    # DC is unreachable, abort
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityResolutionException]{
    # Group identity not resolved, add to list and continue
}
catch {
    # Something else, completely unforeseen, happened, you might want to re-throw and return from your function
}

最后一个catch子句,其中省略了类型列表,称为通用catch子句,并将处理没有&#t; t <的任何异常/ em>匹配任何前面的catch子句。