This is a continuation from another thread. Below is the code I'm currently using.
I've run this, step-by-step, through the debugger in PowerGUI and Powershell Plus. It was easier to see in Powershell Plus as PowerGUI left everything in the foreach scriptblock highlighted during each loop. Anyway...
Everything runs fine, but it seems when it gets to the last account found (which is a local account), its info isn't added to the AdminInfo array.
In the debugger, while going though the loop and after "Name = $name", if I type $name, the correct name is returned. If I type $AdminInfo.name, the previously added name is returned and is the one that is duplicated. This happens on many machines. I don't think it has anything to do with the machine accounts, or SIDs, etc. Perhaps something to do with the enumeration of the accounts?
Would it be "too much work" or "too messy" to do this without the custom object which receives its properties from the array? Along the way I've figured some things out on my own, but I'm hitting a wall right now. Here's the code:
$ErrorActionPreference="SilentlyContinue"
$srcdomain=$env:userdomain
$admins = @()
New-Variable -Name NeverExpiresFlag -value 0x10000 -Option ReadOnly -Force
New-Variable -Name DisabledFlag -value 0x2 -Option ReadOnly -Force
foreach ($computername in get-content .\computers.txt)
{
write-host $computername
$localGroupName = "Administrators"
$group = [ADSI]("WinNT://$computerName/$localGroupName,group")
$grpcount=measure-object $group.members()
$group.Members() |
foreach {
$AdsPath = $_.GetType().InvokeMember('Adspath', 'GetProperty', $null, $_, $null)
$a = $AdsPath.split('/',[StringSplitOptions]::RemoveEmptyEntries)
$name = $a[-1]
$domain = $a[-2]
# Ignore non-local accounts
if ($domain -eq $computerName)
{
$user=([ADSI]"WinNT://$($computername)/$($name)")
$adminInfo = @{
Name = $name;
Computer = $computerName;
PasswordAge = [int]((([ADSI]"WinNT://$($computerName)/$($name)").passwordage[0])/86400)
LastLogin = $(([ADSI]"WinNT://$($computername)/$($name)").lastlogin).tostring()
NeverExpires=[bool]($neverexpiresflag -band $user.userflags[0])
Disabled=[bool]($disabledflag -band $user.userflags[0])
}
$admin = New-Object -TypeName PSObject -Property $adminInfo
$admins += $admin
}
}
}
$date=(get-date -format yyyyMMddHHmm)
$outpath=$srcdomain +"_Admins_"+$date+".csv"
$admins|select name,computer,passwordage,lastlogin,neverexpires,disabled