powershelladsi

Powershell to determine if it is a user or a group from Active Directory


I am trying to create a workaround for Get-LocalGroupMember issue which is described here: https://github.com/PowerShell/PowerShell/issues/2996

After reading that, I came up with this function to get all members from a local group:

function Get-LocalGroupMember2 {
    [CmdletBinding()]
    param
    (
      [Parameter(Mandatory = $true)]
      [string]$Groupname
    )
    
    $group = [ADSI]"WinNT://$env:COMPUTERNAME/$Groupname"
       $members = $group.Invoke('Members') | ForEach-Object {
           $path = ([adsi]$_).path
           Write-Host ">>> $path"
           [pscustomobject]@{
               Computer = $env:COMPUTERNAME
               Domain = $(Split-Path (Split-Path $path) -Leaf)
               User = $(Split-Path $path -Leaf)
           }
       }
   return $members 
}

Here is an example output:

>>> WinNT://MyDomain/TestUser
>>> WinNT://MyDomain/TestGroup

Computer   Domain   User
--------   ------   ----
NyComputer MyDomain TestUser
NyComputer MyDomain TestGroup

Now, I want to know if a member is a user or a group. Something like:

Computer   Domain   Name       Type
--------   ------   ----       ----
NyComputer MyDomain TestUser   User
NyComputer MyDomain TestGroup  Group

Anyone can help?


Solution

  • Slight modification, you can use the .Class property of each member instance:

    function Get-LocalGroupMember2 {
        [CmdletBinding()]
        param(
            [Parameter(Mandatory = $true)]
            [string] $Groupname
        )
    
        $group = [ADSI]"WinNT://$env:COMPUTERNAME/$Groupname"
        $group.Invoke('Members') | ForEach-Object {
            $member = [adsi] $_
            Write-Host ">>> $path"
            [pscustomobject]@{
                Computer = $env:COMPUTERNAME
                Domain   = Split-Path (Split-Path $member.Path) -Leaf
                User     = Split-Path $member.Path -Leaf
                Class    = $member.Class
            }
        }
    }