PowerShell脚本异常:AD员工ID与SQL比对输出所有ID问题排查
Why Your Script Is Outputting All AD Users & How to Fix It
The core issue here is that you're comparing entire objects instead of just the EmployeeID values. Let's break down what's happening and fix it:
Root Cause
$sqlpeepscontains objects returned byInvoke-Sqlcmd, each with anEmployeeIDproperty.$adpeepscontains full AD user objects, each with their ownEmployeeIDproperty.- When you run
$_ -notin $sqlpeeps, you're checking if the entire AD user object exists in the SQL object collection—which it never will, since they're different object types. That's why every AD user passes the filter.
Corrected Script
Here's the fixed version with clear explanations:
# Import the Active Directory module Import-Module ActiveDirectory # Fetch EmployeeIDs from SQL, extract just the ID values (not full objects) $sqlpeeps = Invoke-Sqlcmd -ServerInstance '192.168.1.1' -Database 'COMPANY' -Query "SELECT EmployeeID FROM [COMPANY].[dbo].[employee] WHERE [EmployeeStatus] in ('A', 'S', 'L')" $sqlEmployeeIDs = $sqlpeeps | Select-Object -ExpandProperty EmployeeID # Fetch AD users with EmployeeID property, filter out those without an ID $adpeeps = Get-ADUser -Filter * -SearchBase "OU=OU,OU=OU,OU=OU,DC=DC,DC=COM" -Properties 'EmployeeID' | Where-Object { $_.EmployeeID -ne $null } # Compare just the EmployeeID values to find AD users not in SQL $adpeeps | Where-Object { $_.EmployeeID -notin $sqlEmployeeIDs } | Out-Host
Key Changes Explained
Extract SQL EmployeeID Values:
Select-Object -ExpandProperty EmployeeIDconverts the SQL object collection into a simple array ofEmployeeIDstrings/numbers. This lets us compare just the IDs instead of full objects.
Filter AD Users Without EmployeeID:
- Adding
Where-Object { $_.EmployeeID -ne $null }ensures we only consider AD users who actually have an EmployeeID set (since users without one can't be in your SQL list anyway).
- Adding
Compare Correct Properties:
- Changed
$_ -notin $sqlpeepsto$_.EmployeeID -notin $sqlEmployeeIDs—now we're comparing the AD user's EmployeeID directly against the list of SQL IDs.
- Changed
Edge Cases to Consider
- Data Type Mismatches: If your SQL
EmployeeIDis an integer but AD stores it as a string, you might need to convert one to match the other (e.g.,[string]$_.EmployeeID -notin $sqlEmployeeIDsor[int]$_.EmployeeID -notin $sqlEmployeeIDs). - Case Sensitivity: PowerShell's
-notinis case-insensitive by default, but if your IDs are case-sensitive (unlikely for EmployeeIDs), you can use-cnotininstead.
内容的提问来源于stack exchange,提问作者MutinyMate
相关产品推荐
相关产品推荐

