Skip to content

Instantly share code, notes, and snippets.

@jmconway
Created June 19, 2021 14:32
Show Gist options
  • Save jmconway/18989b112bea439a6e7d3702d4ac9685 to your computer and use it in GitHub Desktop.
Save jmconway/18989b112bea439a6e7d3702d4ac9685 to your computer and use it in GitHub Desktop.
Function to take a given txt or csv file and compare it against your Active Directory.
# Function to take a given txt or csv file and compare it against Active Directory
# Requires the Active Directory PowerShell Module
# EXAMPLE: Compare-ADFromFile -File .\affected_user_accounts.txt
function Compare-ADFromFile {
# Path to the file of names to compare against AD
[CmdletBinding()]
param (
[Parameter(Position=0, Mandatory, ValueFromPipeline)]
[System.String[]]
$File
)
# Get Names
$names = Get-Content -Path $File
# Make sure we have the AD Powershell Module
Import-Module ActiveDirectory
# Iterate through all usernames
$output = foreach ($name in $names) {
# If the user does exist in AD, gather all properties. Tweak the Properties parameter to your needs.
try {
Get-ADUser $name -Properties * -ErrorAction SilentlyContinue | Select-Object * | Sort-Object -Property SamAccountName
} # If the user does not exist in AD, just give a simple message in the console
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
Write-Host "$name does not appear in your Active Directory"
} # If all else fails...
catch {
Write-Host "Something else went wrong while searching for $name"
}
# Export to CSV
$output | Export-Csv -Path ".\Compare-ADFromFile_output.csv"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment