Public/Get-UserGroup.ps1
|
function Get-UserGroup { <# .SYNOPSIS Gets local groups from the Windows Security Accounts Manager. .DESCRIPTION The Get-UserGroup cmdlet gets local groups from the Windows Security Accounts manager. .PARAMETER Name Specifies the local groups to get from the local Security Accounts Manager. .PARAMETER SID Specifies a local group from the local Security Accounts Manager by SecurityIdentifier. .EXAMPLE Get-UserGroup Gets all local groups. .EXAMPLE Get-UserGroup -Name "Administrators" Gets the local group named Administrators. #> [CmdletBinding(DefaultParameterSetName = 'Default')] param( [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'Default')] [string[]]$Name, [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'SecurityIdentifier')] [System.Security.Principal.SecurityIdentifier[]]$SID ) process { try { # If no parameters, get all groups if ($null -eq $Name -and $null -eq $SID) { return [LocalAccountHelper]::GetAllUserGroups() } # Process by name if ($null -ne $Name) { foreach ($groupName in $Name) { if ([string]::IsNullOrWhiteSpace($groupName)) { continue } # Check for wildcard if ($groupName -match '\*|\?') { $pattern = [System.Management.Automation.WildcardPattern]::new($groupName, [System.Management.Automation.WildcardOptions]::Compiled -bor [System.Management.Automation.WildcardOptions]::IgnoreCase) $allGroups = [LocalAccountHelper]::GetAllUserGroups() foreach ($g in $allGroups) { if ($pattern.IsMatch($g.Name)) { $g } } } else { $group = [LocalAccountHelper]::GetUserGroupByName($groupName) if ($null -ne $group) { $group } else { $ex = [GroupNotFoundException]::new($groupName, $groupName) Write-Error -Message $ex.Message -ErrorId 'GroupNotFound' -Category ObjectNotFound -TargetObject $groupName } } } } # Process by SID if ($null -ne $SID) { foreach ($groupSid in $SID) { if ($null -eq $groupSid) { continue } $group = [LocalAccountHelper]::GetUserGroupBySid($groupSid) if ($null -ne $group) { $group } else { $ex = [GroupNotFoundException]::new($groupSid.Value, $groupSid) Write-Error -Message $ex.Message -ErrorId 'GroupNotFound' -Category ObjectNotFound -TargetObject $groupSid } } } } catch { # Let the specific error IDs propagate up without overwriting throw } } } |