At the risk of earning me another necromancer-badge I'd like to provide some more up to date and more idiomatic code to answer the question.
Get-LocalGroup |
Where-Object { (Get-LocalGroupMember $_).name -eq "$env:COMPUTERNAME\$env:USERNAME" }
$env:USERNAME
can of course be replaced by any other username.
Using operators like -eq
or -match
with arrays is what makes the not so obvious part in the above example since they return arrays which - if empty - are an equivalent of $false
in a boolean context and $true
otherwise (the operator is applied to each item and the item gets part of the resulting array if the operator returns $true
):
@(1;2;3) -eq 2 # => @(2)
@(1;2;3) -eq 4 # => @()
@(1;2;3) -ge 2 # => @(2;3)
Another example of Powershell-array-magic that happens here is that a method that is called on an array object that is not a member of the array object is called on each item of that object and the return value is an array of the respective return values that are not $null
. So for example (Get-LocalGroup).sid.value
returns an array of strings like:
S-1-5-32-544
S-1-5-32-545
S-1-5-32-546
...
I hope this explains the (Get-LocalGroupMember $_).name
part in a digestable way.
All users and their groups:
Get-LocalUser |
ForEach-Object {
$nm = $_.name
[pscustomobject]@{
Name = $nm
Groups = Get-LocalGroup |
Where-Object { (Get-LocalGroupMember $_).name -contains "$env:COMPUTERNAME\$nm" } |
ForEach-Object name
}
}