获取属于本地组成员的域用户的 DisplayName

获取属于本地组成员的域用户的 DisplayName

我有一个脚本,其中列出了所有本地组及其成员并提供 CSV 输出。

我修改了脚本以获取本地组的域用户成员的 displayName 属性(不是域组,不是本地组,也不是本地用户。只是域用户的 displayName)

但该脚本运行不稳定。它为每个成员显示相同的显示名称,而不检查它是域对象还是本地对象。或者不检查它是组还是用户。

有什么建议可以帮助我实现目标吗?

$complist = get-content C:\temp\comps2.txt
foreach ($comp in $complist){

$strComputer = $comp #Enter the name of the target computer, localhost is used by default
Write-Host "Computer: $strComputer"
$computer = [ADSI]"WinNT://$strComputer"
$objCount = ($computer.psbase.children | measure-object).count
Write-Host "Q-ty objects for computer '$strComputer' = $objCount"
$Counter = 1
$result = @()
foreach($adsiObj in $computer.psbase.children)
{
switch -regex($adsiObj.psbase.SchemaClassName)
  {
    "group"
    {
      $group = $adsiObj.name
      $LocalGroup = [ADSI]"WinNT://$strComputer/$group,group"
      $Members = @($LocalGroup.psbase.Invoke("Members"))
      $objCount = ($Members | measure-object).count
      Write-Host "Q-ty objects for group '$group' = $objCount"
      $GName = $group.tostring()

      ForEach ($Member In $Members) {

      
        $Name = $Member.GetType().InvokeMember("Name", "GetProperty", $Null, $Member, $Null)
        $Path = $Member.GetType().InvokeMember("ADsPath", "GetProperty", $Null, $Member, $Null)
        $membername= Get-ADUser $name -Properties displayname | Select-Object -ExpandProperty displayname
        
        Write-Host " Object = $Path"

                 $isGroup = ($Member.GetType().InvokeMember("Class", "GetProperty", $Null, $Member, $Null) -eq "group")

                


        If (($Path -like "*/$strComputer/*") -Or ($Path -like "WinNT://NT*")) { $Type = "Local"
        } Else 
        
        {$Type = "Domain"}

        

        

        $result += New-Object PSObject -Property @{
          Computername = $strComputer
          NameMember = $Name
          PathMember = $Path
          TypeMemeber = $Type
          ParentGroup = $GName
          isGroupMemeber = $isGroup
          Depth = $Counter
          Membername = $membername

        }
      }
    }
  } #end switch
  
} #end foreach

Write-Host "Total objects = " ($result | measure-object).count
$result = $result | select-object Computername, ParentGroup, NameMember, TypeMemeber, PathMember, isGroupMemeber, membername
$result | Export-Csv -append -path ("C:\temp\LocalGroups({0})-{1:yyyyMMddHHmm}.csv" -f
$env:COMPUTERNAME,(Get-Date)) -Delimiter ";" -Encoding "UTF8" -force -NoTypeInformation}

答案1

我可以建议另一种方法吗:

  1. 使用 Get-LocalGroup cmdlet 查询所有本地组(foreach 循环)
  2. 使用 Get-LocalGroupMember 查询当前组的成员Use Get-LocalGroupMember to query members of the current group

您可以过滤内容

(Get-LocalGroupMember -Group $Group.Name).Name | Select-String -Pattern "MyDomain\*"

并将结果放入 中PSCustomObject

相关内容