简体   繁体   中英

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 :(

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM