I am trying to export certain users' SamAccountName and EmployeeNumber from AD to csv. I only have EmployeeNumbers from HR in csv file and have to match it to SamAccountName in AD. My code does not work past 'if' condition. When I echo output there are same values for $a and $b all in String type. This file C:\temp\UsersToDisable.csv contains 4 and 3 number with column name "EmployeeNumber". This is what i came up with:
Import-Module ActiveDirectory
$Nums = Import-Csv "C:\powershell\EmployeeNumbers.csv"
$Users = Get-ADUser -Filter "*" -Property EmployeeNumber -SearchBase
"DC=my,DC=example,DC=com" | Where { $_.EmployeeNumber -ne $null } |
Select SamAccountName,EmployeeNumber
Foreach ($user in $Users)
{
$EmployeeNumber = $user.EmployeeNumber
foreach ($Line in $Nums)
{
$number = $line.EmployeeNumber
$a = $number.toString()
$b = $EmployeeNumber.toString()
echo $a $b
if($a -eq $b)
{
echo $user.SamAccountName
$result = ,(Get-ADUser $user.SamAccountName -Properties * | Select SamAccountName,employeeNumber)
}
}
} $result | Export-CSV "C:\temp\CCI_All_Users.csv" -NoTypeInformation
Thank you for any advice!
CodePudding user response:
Loading all the users from the directory and then searching once again for the same user in the directory is not an ideal solution for performance reason.
Try the following code. For each number from the input file, search in the directory the user having the current EmployeeNumber, requesting to load the EmployeeNumber property. Then select only the desired properties and export them to CSV.
Import-Module ActiveDirectory
$Nums = Import-Csv "C:\powershell\EmployeeNumbers.csv"
$Nums | ForEach-Object {
Get-ADUser -LdapFilter "(EmployeeNumber=$_)" -Property EmployeeNumber -SearchBase "DC=my,DC=example,DC=com" |
Select-Object SamAccountName, EmployeeNumber
} | Export-CSV "C:\temp\CCI_All_Users.csv"
CodePudding user response:
An alternative to Hazrelle's helpful answer, very similar but instead of looping over each line of the CSV, taking advantage of the LDAPFilter
capabilities with the help of some string manipulation:
# This assumes there is a column named "EmployeeNumber" in the CSV
$Nums = (Import-Csv "C:\powershell\EmployeeNumbers.csv").EmployeeNumber
# Assuming Nums is an Array with Employee Numbers. i.e.:
# $Nums => A123,A456,A789
# $filter would look like this:
# (|(employeenumber=A123)(employeenumber=A456)(employeenumber=A789))
$filter = [string]::Format(
'(|(employeenumber={0}))',
($Nums -join ')(employeenumber=')
)
$params = @{
Properties = 'EmployeeNumber'
SearchBase = 'DC=my,DC=example,DC=com'
LDAPFilter = $filter
}
Get-ADUser @params | Select-Object samAccountName, EmployeeNumber |
Export-CSV "C:\temp\CCI_All_Users.csv" -NoTypeInformation
Now to explain the error where the error could be, you're using -Property
on Get-ADUser
where it should -Properties
. This causes $EmployeeNumber = $user.EmployeeNumber
to be $null
.
Worth mentioning, $result = ,(Get...
is not recommended.