A customer had partially implemented a (written) policy in the past where the the Local Administrator account was renamed according to a special convention.
This policy stated that the Administrator account needed to be renamed to admin with the computername as a prefix.
However they didn’t know exactly on which machines this policy had been applied to in the past. I was asked to write a script that would check a list of machine names, query the Administrator account name and write this in a new list.
The Administrator account has a Well Known SID of S-1-5-21-xxxxxxx-500 where xxxxxxx is the SID of the computer.
This makes this an easy task for PowerShell: we use the Win32_UserAccount WMI Class and filter this on ‘S-1-5-%-500’:
Here is the script:
# Output Folder
$fldr = "c:\Users\rweijnen\Projecten\Customer\scripts"
# I am not in the domain so I am using explicit credentials that I saved to a file
$password = Get-Content "$fldr\da-password.bin" | ConvertTo-SecureString
$Credential = New-Object System.Management.Automation.PsCredential("da-weijnen", $password)
# The Domain
$Domain = "CONTOSO"
# The function that does the actual work...
function GetLocalAdmin([string]$Computer)
{
try
{
# Perform remote WMI Query using Domain Credentials, query is filtered
$ColItems = Get-WmiObject -Class Win32_UserAccount -Authority "ntlmdomain:$Domain" -Namespace "root\cimv2" -ComputerName $Computer -Credential $credential -Filter "SID like 'S-1-5-%-500'" -ErrorAction:Stop
$item | Add-Member -Type NoteProperty -Name "Error" -Value "None"
return $ColItems.Name
}
catch [System.Exception]
{
$item | Add-Member -Type NoteProperty -Name "Error" -Value $_.Exception.Message
return "Unknown"
}
}
# Create array
$collection = @()
# Import CSV, ; seperated contains the following columns
# Hostname;IP
$csv = Import-Csv "$fldr\Wmi.csv" -Delimiter ";"
[int]$i = 0
foreach ($entry in $csv)
{
$i++
$item = New-Object System.Object
$item | Add-Member -Type NoteProperty -Name "Hostname" -Value $entry.Hostname
$item | Add-Member -Type NoteProperty -Name "IP" -Value $entry.IP
$item | Add-Member -Type NoteProperty -Name "AdminName" -Value (GetLocalAdmin $entry.Hostname)
if ($item) {$collection += $item}
$item
}
# Write new CSV
$collection | Export-Csv "$fldr\AdminAccounts.csv" -Delimiter ";"