Search code examples
powershellactive-directorypowershell-2.0powershell-3.0

Get SamAccountName from AD


I need some help with this script.

I'm trying to take some csv file found user with employeeid and get back SamAccountName, DisplayName to csv file.

 $csv_data = Import-Csv -Path C:\Scripts\test2.scv -Delimiter "," | Select-Object DisplayName ,SamAccountName | Out-File -FilePath C:\Scripts\test3.scv

example scv

Import-CSV -Path "$home\desktop\Scripts\test5.scv" | ForEach-Object {

$ADUserObject = Get-ADUser -Filter "employeeID -eq '$($_.employeeID)'" -Properties employeeID, sAMAccountName -ErrorAction SilentlyContinue

}

maybe something like this, but still not working :(


Solution

  • I think you were pretty close, or maybe even there already. But here's a clean way to do it. Also note that you use '.scv' instead of '.csv', don't know if that is intended.

    $csv = Import-CSV -Path "$home\desktop\Scripts\test5.csv"
    $csvOutput = "$home\desktop\Scripts\test3.csv"
    $object = @()
    foreach($employee in $csv){
        $ADUserObject = Get-ADUser -Filter "employeeID -eq '$($employee.employeeID)'" -Properties samAccountName, displayName -ErrorAction SilentlyContinue
        if($ADUserObject){
            $object += New-Object psobject -Property @{
                displayName = $ADUserObject.displayName
                samAccountName = $ADUserObject.SamAccountName
            }
        }else{
            Write-Host "No employee found for $($employee.employeeId)" -ForegroundColor Red
        }
    }
    if($object){
        $object | Select-Object displayName, samAccountName | Export-Csv -Path $csvOutput -Delimiter "," -Encoding UTF8 -NoTypeInformation
    }
    

    Note that you can use '-append' to add the content to the csv instead of overwriting it.

    Hope this helps!