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;