Author: Malte Bublitz
Language/File type: PowerShell
Description
▶ Export a list of all users and groups and their corresponding SIDs to CSV files.
This PowerShell script creates two CSV files inside a new folder, “My Documents\WindowsLocalAccounts”, named LocalUsers.csv and LocalGroups.csv
The group list contains only the group name and SID; whereas the user list additionally contains the names of all groups which the user is part of.
Note: To support pasting this snippets directly inside your PowerShell session, without leaving you inside the WindowsLocalAccounts folder, Push-Location is used.
⇒ Documentation for the PowerShell Cmdlets used:
Get-LocalUser: <https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/get-localuser?view=powershell-5.1>
Get-LocalGroup: <https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/get-localgroup?view=powershell-5.1>
Get-LocalGroupMember: <https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/get-localgroupmember?view=powershell-5.1>
Export-Csv: <https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-7.5>
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#
# Create a new folder for the CSV files inside the user's MyDocuments-Folder
#
Write-Host -Message "Creating destination folder WindowsLocalAccounts inside your Documents folder."
New-Item -ItemType Directory -Path ([Environment]::GetFolderPath("MyDocuments")) -Name WindowsLocalAccounts
#
# Go to the new folder
#
Push-Location "$([Environment]::GetFolderPath("MyDocuments"))\WindowsLocalAccountInfo"
Write-Host "Destination path for the CSV files: $(Get-Location)"
#
# Get all active user accounts, including their SIDs and group memberships.
#
Write-Host -Message "Exporting a list of all active local user accounts including their group memberships"
Get-LocalUser |
ForEach-Object {
$user = $_
return [PSCustomObject]@{
"User" = $user.Name
"SID" = $user.SID
"Groups" = ((Get-LocalGroup |
Where-Object {
$user.SID -in ($_ | Get-LocalGroupMember | Select-Object -ExpandProperty "SID")
} |
Select-Object -ExpandProperty "Name" |
Out-String
) -replace '\r\n', ' ').Trim(" ")
}
} | Export-Csv -Path LocalUsers.csv
#
# Export local groups and their SIDs
#
Write-Host -Message "Exporting all local groups and their SIDs"
Get-LocalGroup | Select-Object -Property Name,SID | Export-Csv -Path LocalGroups.csv
#
# Return to previous location
#
Pop-Location