I'm not sure where my logic is off? The idea behind this script is to locate all of our admin accounts that are associated with a disabled user account. We use codes for SamAccountName, but the admin accounts end with -a, -d, -e for our IT admins. I thought if I looked at all the disabled users and created and array, then grabbed all the enabled admin accounts, then did a lookup where the first 9 numbers matched, I would get a list back with disabled users who had an enabled admin account. Instead, I get matches on both accounts disabled and only via Excel can I see the ones that have an associated enabled admin account. Why is my method not working as I intend? Thx
$Users1 = Get-ADUser -Filter {enabled -eq $False} -Properties SamAccountName, name, title, enabled,lastlogondate,accountexpirationdate | select SamAccountName, name, title,enabled,lastlogondate, accountexpirationdate
$Users2 = Get-ADUser -Filter {samaccountname -like "*-a" -or samaccountname -like "*-d" -or samaccountname -like "*-e" -and enabled -eq $True} -Properties SamAccountName, name, title,enabled, lastlogondate,accountexpirationdate | select SamAccountName, name,enabled, title,lastlogondate, accountexpirationdate
$output = "C:\scripts\adcleanup\Admin-Accounts-Need-Term_$((Get-Date).ToString('MM-dd-yyyy')).csv"
$SIDTable = @{}
$Users1 | ForEach-Object {
$SIDTable[$_.SamAccountName] = $_
}
$matching = ForEach ($User in $Users2) {
$SID = $User.SamAccountName.Substring(0,8)
If ($SIDTable.containskey($SID)) {
$SIDTable[$SID] | Select @{Name="SID";Expression={$user.SamAccountName}},SamAccountName,@{Name="Admin Enabled";Expression={$user.enabled}},"Enabled","Name", "Title", "LastLogonDate", "AccountExpirationDate"
}}
$matching | Export-csv $output -NoTypeInformation
$string = Substring(0,8)will give you the first 8 characters of$string. Unless you are absolutely sure that the samaccountname is always 8 or 9 characters, you'd rather want to remove the last-a(or-d/-e):$string.Remove($string.IndexOf('-'))- Mathias R. Jessen