Active Directory Using PowerShell
Prerequisites
- PowerShell 5.1 or PowerShell 7+
- RSAT Active Directory module installed (Windows Server or Windows 10/11 with RSAT)
- Read access to Active Directory
- The exported agents CSV file
The Script
$CSVPath = "C:\Temp\Agents.csv"
$OutputPath = "C:\Temp\agents_updated.csv"
$LogPath = "C:\Temp\agents_ad_check.log"
Import-Module ActiveDirectory
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$line = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] [$Level] $Message"
Write-Host $line
Add-Content -Path $LogPath -Value $line
}
function Get-ADUserStatus {
param([string]$UserEmail)
# Check 1: Skip empty or whitespace values
if ([string]::IsNullOrWhiteSpace($UserEmail)) { return "not-exist" }
# Check 2: Domain normalization — replace legacy domain with current domain
if ($UserEmail -like "*@olddomain.com") {
$UserEmail = $UserEmail.Replace("@olddomain.com", "@newdomain.com")
}
try {
# Primary lookup: by UserPrincipalName
$user = Get-ADUser -Filter "UserPrincipalName -eq '$UserEmail'" `
-Properties Enabled -ErrorAction Stop
# Fallback lookup: by mail attribute
if ($null -eq $user) {
$user = Get-ADUser -Filter "mail -eq '$UserEmail'" `
-Properties Enabled -ErrorAction Stop
}
if ($user.Enabled -eq $true) { return "exist" } else { return "not-exist" }
}
catch {
Write-Log "ERROR: '$UserEmail' — $($_.Exception.Message)" -Level "ERROR"
return "not-exist"
}
}
$records = Import-Csv -Path $CSVPath
foreach ($row in $records) {
$row.Is_Owner_Exist = Get-ADUserStatus -UserEmail $row.Owner.Trim()
Write-Log "$($row.Owner) → $($row.Is_Owner_Exist)"
}
$records | Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8
Write-Log "=== Done. Output: $OutputPath ==="
PowerShell, ActiveDirectory, CopilotStudio, PowerPlatform, MicrosoftCopilot, EntraID, M365Governance, PowerShellAutomation, MicrosoftTeams, LowCode
No comments:
Post a Comment