1

I wanted to get the groups of a local user account in windows.This can be done if we get the native object from the directory entry. This is achieved in the following way through APIs :

DirectoryEntry comp = new DirectoryEntry("WinNT://computername");
DirectoryEntry de = comp.Children.Find("account19", "user");     
IADsUser NativeObject = (IADsUser)directoryentry.NativeObject;

But how to get the same thing through powershell script?

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
cmm user
  • 2,426
  • 7
  • 34
  • 48
  • um.. maybe in powershell there's anther way to accomplish task on domain/local users using `[ADSI]`. Could you tell what's you final goal with `NativeObject`? – CB. Jan 23 '14 at 08:04
  • To get the groups of a user. One way is to get all the groups. Then their members and check if the user is a part of that group.But this is not efficient. – cmm user Jan 23 '14 at 13:39
  • This should help: http://stackoverflow.com/questions/4548476/powershell-list-local-users-and-their-groups – Raf Jan 23 '14 at 15:24

1 Answers1

0

You can use the Microsoft .NET Framework types in the System.DirectoryServices.AccountManagement namespace to obtain local group memberships. I wrote a simple PowerShell advanced function that will retrieve the group memberships for a local user account.

Note: Because we are using the GetGroups() method on the UserPrincipal class, this code is very efficient. You do not need to get a list of all groups, and then iterate over them, as previously suggested in the comments.

function Get-LocalUserGroupMembership {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        [string] $Identity = $env:USERNAME
    )

    # Import the System.DirectoryServices.AccountManagement .NET library
    Add-Type -AssemblyName System.DirectoryServices.AccountManagement;

    # Get a reference to the local machine's Security Account Manager (SAM)
    $PrincipalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList ([System.DirectoryServices.AccountManagement.ContextType]::Machine);
    # Get a reference to a specific user principal, based on its account name
    $UserAccount = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($PrincipalContext, $Identity);
    if (!$UserAccount) {
        throw 'User account could not be found!';
    }

    # Call the GetGroups() method on the UserPrincipal object
    $GroupList = $UserAccount.GetGroups();

    # Output the list of groups
    Write-Output -InputObject $GroupList;
}

Get-LocalUserGroupMembership;
  • I tried the above script.I am getting the following exception : "Unhandled Exception: System.Management.Automation.RemoteException: User account could not be found!" – cmm user Jan 24 '14 at 05:49