I'd like to have a report with all the local users and their relative groups (users, power users, administrators and so on.
I get the users in this way:
$adsi = [ADSI]"WinNT://."
$adsi.psbase.children | where {$_.psbase.schemaClassName -match "user"} | select @{n="Name";e={$_.name}}
but I don't know how to retrieve their groups. Thanks in advance.
This question is related to
powershell
user-accounts
Expanding on mjswensen's answer, the command without the filter could take minutes, but the filtered command is almost instant.
PowerShell - List local user accounts
Fast way
Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True'" | select name, fullname
Slow way
Get-WmiObject -Class Win32_UserAccount |? {$_.localaccount -eq $true} | select name, fullname
Update as an alternative to the excellent answer from 2010:
You can now use the Get-LocalGroupMember, Get-LocalGroup, Get-LocalUser etc. to get and map users and groups
Example:
PS C:\WINDOWS\system32> Get-LocalGroupMember -name users
ObjectClass Name PrincipalSource
----------- ---- ---------------
User DESKTOP-R05QDNL\someUser1 Local
User DESKTOP-R05QDNL\someUser2 MicrosoftAccount
Group NT AUTHORITY\INTERACTIVE Unknown
You could combine that with Get-LocalUser. Alias glu can also be used instead. Aliases exists for the majority of the new cmndlets.
In case some are wondering (I know you didn't ask about this) Adding users could be for example done like so:
$description = "Netshare user"
$userName = "Test User"
$user = "test.user"
$pwd = "pwd123"
New-LocalUser $user -Password (ConvertTo-SecureString $pwd -AsPlainText -Force) -FullName $userName -Description $description
For Googlers, another way to get a list of users is to use:
Get-WmiObject -Class Win32_UserAccount
try this one :),
Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }
Use this to get an array with the local users and the groups they are member of:
Get-LocalUser |
ForEach-Object {
$user = $_
return [PSCustomObject]@{
"User" = $user.Name
"Groups" = Get-LocalGroup | Where-Object { $user.SID -in ($_ | Get-LocalGroupMember | Select-Object -ExpandProperty "SID") } | Select-Object -ExpandProperty "Name"
}
}
To get an array with the local groups and their members:
Get-LocalGroup |
ForEach-Object {
$group = $_
return [PSCustomObject]@{
"Group" = $group.Name
"Members" = $group | Get-LocalGroupMember | Select-Object -ExpandProperty "Name"
}
}
Source: Stackoverflow.com