I am trying to use powershell to find the users that has been newly added to an Active directory group. I export the membership of the groups daily into a csv and is now trying to get the newly added group members by comparing the previous day's and the current day's csv file.
Here is the function I use to check if the a user from the current day's csv does not exist on the previous day's csv (which means that they are newly added).
$file1 = Import-Csv -path "C:\test\members_previous.csv"
$file2 = Import-Csv -path "C:\test\members_Current.csv"
foreach ($Item in $file2.samaccountname)
{
if ($Item -in $file1.samaccountname)
{
$true
}
else
{
$item
}
}
export-csv -path "C:\test|result.csv" -NoTypeInformation
The csv file from the export does not contain anything inside.
I'm not sure how I can export only the results of the else statement into a csv. The "$item" value in the else statement contains the samaccountname of the user.
I think the solution might be simple, but I can't figure it out.
Thank you in advance for any suggestion!
CodePudding user response:
I will assume there is something missing in your question's code, Export-Csv
will require an "Input Object" to perform any operation and currently there is none.
What you're looking to do can be simplified using Where-Object
to filter all objects where the samaccountname
values are not present in the reference CSV (previous day):
$ref = Import-Csv "C:\test\members_previous.csv"
Import-Csv "C:\test\members_Current.csv" |
Where-Object { $_.samaccountname -notin $ref.samaccountname } |
Export-Csv C:\test\result.csv -NoTypeInformation
If both CSVs are really big, then you might want to change the code a bit so it's more efficient:
$ref = Import-Csv "C:\test\members_previous.csv" |
Group-Object samaccountname -NoElement -AsHashTable -AsString
Import-Csv "C:\test\members_Current.csv" |
Where-Object { -not $ref.ContainsKey($_.samaccountname) } |
Export-Csv C:\test\result.csv -NoTypeInformation
CodePudding user response:
A little improvement on @santiagosquarzon answer.
# Create output file
$outFile = "c:\test\report.csv"
$outData = New-Object -TypeName System.Text.StringBuilder
[void]$outData.AppendLine("samAccountName,Status")
# Create the dictionary based on the previous members results
$content = Import-CSV -Path c:\test\members_previous.csv
$lookup = $content | Group-Object -AsHashTable -AsString -Property samAccountName
$count = 0
# Start cycling through the master list
Import-Csv -Path c:\test\members_current.csv | foreach {
$samAccountname = $PSItem.samaccountname
$found = $lookup[$samAccountname]
if ($found)
{
$status = "Match"
}
else
{
$status = "No Match"
$count
}
[void]$outData.AppendLine("`"$samAccountName`",`"$status`"")
}
# Write the output to a file
$outData.ToString() | Out-File -FilePath $outFile -Encoding ascii
Write-Host "Found $count unmatched systems" -ForegroundColor Yellow