I'm trying to generate a report for all disabled accounts that don't have the group "Terminated Employees" but it isn't seeming to generate the report. Below is the code that I have at the moment.
TLDR: The text file contains a list of all the disabled accounts and I am trying to cross reference that list with the list of people in Terminated Employees and then return to a CSV file the accounts that are in that list and not in the group "Terminated Employees".
Also note that we need to bypass the limit of Get-ADGroupMember
as there are over 5000 members in this group.
$ADGroupName = "Terminated Employees"
$users = Get-Content C:\Shortcuts\users.txt
$InputPath= "C:\Scripts\T_Accounts.csv"
$a = @(Get-ADGroup $ADGroupName | Select-Object -ExpandProperty Member)
foreach ($user in $users) {
if ($a -contains $user) {
"Member found"
} else {
$SplitStep1 = ($Member -split ",",2)[0]
$SplitStep2 = ($SplitStep1 -split "=",2)[1]
$SplitStep2 = $SplitStep2 | Out-File -Append $InputPath
}
}
foreach ($value in (Get-Content $InputPath)) {
$b = Get-ADUser -Identity $value -Properties DisplayName, sAMAccountName, LastLogonDate, Enabled
}
I suggest using Import-Csv
and Export-Csv
cmdlets handling input and output files. And if we are searching disabled user accounts, which are members of specific group, there should be no need for the input file at all.
How about this oneliner:
Get-ADGroup "Terminated Employees" -Properties Members |
Select-Object -ExpandProperty Members |
Get-ADUser -Properties Enabled, Displayname, LastLogonDate |
Where-Object {$_.Enabled -eq $false} |
Select-Object DisplayName, SamAccountName, LastLogonDate, Enabled |
Export-Csv outfile.txt
Edit: Should have internalized the original question before rushing to answer. I think the clearest way is to create two sets of users and compare them, exporting results to CSV file.
$disabledusers = Get-Aduser -filter "Enabled -eq '$false'" -properties
DisplayName, SamAccountName, LastLogonDate, Enabled | select DisplayName,
SamAccountName, LastLogonDate, Enabled
$groupmembers = Get-ADGroup "Terminated Employees" -Properties Members|
Select-Object -ExpandProperty Members | Get-ADUser -Properties DisplayName,
sAMAccountName, LastLogonDate, Enabled | select DisplayName, SamAccountName,
LastLogonDate, Enabled
Compare-Object $groupmembers $disabledusers -Property enabled -PassThru |
?{$_.sideindicator -eq "=>"} | select DisplayName, SamAccountName,
LastLogonDate, Enabled | export-csv outfile.txt