I have a huge list of users that are present within an application, and I need to check whether all of them are present within on-Premises Active Directory. There's no way I'm going to be copying/pasting each individual User ID into AD and checking whether they're there or not.
The spreadsheet I have been given lists the users by sAMAccountName, so I will need to import the list via a CSV, get PowerShell to check whether each individual user exists, and then report back with a confirmation of each user being either "active" or "deleted".
If I can get PowerShell to return this as a list or export the data into a new CSV file then even better.
What's the easiest way of doing this? I have got as far as the following, but I'm stuck!
Import-CSV "\\tsclient\C:\Users\abc\123.csv" | foreach-object {Get-ADUser -Filter { SamAccountName -eq $SamAccountName }).Count -eq 0) { Write-Warning -Message "User $SamAccountName does not exist." }
I know this isn't right before running and will just error. I'm not clued up enough on arrays either to check if this would make it simpler.
Overall though, the process and end goal seems pretty simple, I just can't quite get there!
Thank you!
It seems what you want is output in an odered CSV file you can double-click to open in Excel with three (or more if you need that) properties:
Assuming the field in the CSV is called SamAccountName
:
If the field has a different header, use that instead
$result = Import-CSV "\\tsclient\C$\Users\abc\123.csv" | ForEach-Object {
$user = Get-ADUser -Filter "SamAccountName -eq '$($_.SamAccountName)'"
if ($user) { $user | Select-Object Name, SamAccountName, Enabled }
else {
Write-Warning -Message "User '$($_.SamAccountName)' does not exist."
# output an error object
"" | Select-Object Name, @{Name = 'SamAccountName'; Expression = {$_.SamAccountName}}
@{Name = 'Enabled'; Expression = { 'User does not exist' }}
}
}
# now you can output the results on screen
$result | Format-Table -AutoSize
# or save this to a CSV file you can open in Excel
$result | Export-Csv -Path 'X:\Somewhere\Users.csv' -NoTypeInformation -UseCulture