Mikke
Mikke

Reputation: 21

How to get samaccountname from an e-mail using Powershell?

I have a .txt file with a bunch of email addresses and I need get corresponding login names and export them into another file.

I wrote a script that looks something like that:

Import-Module ActiveDirectory

$users = get-content C:\users-input.txt

foreach($users in $users){

Get-ADUser -Filter {EmailAddress -eq "$_"} -properties SamAccountName | Select-Object SamAccountName | Export-CSV -Path "c:\users.csv"

}

By some reason, I only get an empty file as the result. Anyone can tell me what do I do wrong?

Upvotes: 2

Views: 38549

Answers (2)

Bill_Stewart
Bill_Stewart

Reputation: 24525

You need to Export-Csv at the end so that you don't overwrite it for each iteration of the loop. Example:

Get-Content "C:\Scripts\users-input.txt" |
  ForEach-Object { Get-ADUser -LDAPFilter "(mail=$_)" } |
  Select-Object sAMAccountName |
  Export-Csv "C:\Scripts\users-output.csv" -NoTypeInformation

That will create a CSV file with only a single column (sAMAccountName). Not that useful. If you want just a list of usernames, use Out-File, like:

Get-Content "C:\Scripts\users-input.txt" |
  ForEach-Object { Get-ADUser -LDAPFilter "(mail=$_)" } |
  Select-Object -ExpandProperty sAMAccountName |
  Out-File "C:\Scripts\users-output.txt"

But then you have two separate files without a good way to correlate them without iterating the input file again. Perhaps better is to create an output file with both the mail and sAMAccountName attributes?

Get-Content "C:\Scripts\users-input.txt" | ForEach-Object {
  $mail = $_
  $user = Get-ADUser -LDAPFilter "(mail=$mail)"
  if ( $user ) {
    $sAMAccountName = $user.sAMAccountName
  }
  else {
    $sAMAccountName = $null
  }
  [PSCustomObject] @{
    "mail" = $mail
    "sAMAccountName" = $sAMAccountName
  }
} | Export-Csv "C:\Scripts\users-output.csv" -NoTypeInformation

A bit more code but a good benefit. This output file contains both mail and sAMAccountName. If the mail lookup fails, the sAMAccountName attribute will be empty on that row.

Upvotes: 3

Ashigore
Ashigore

Reputation: 4678

Several problems here,

You use the variable $_ as the email address in the Get-ADUser command but this isn't defined as it's only used in loops using ForEach-Object.

You are using the same variable name in your foreach so the first loop overwrites the array being looped.

You are writing the CSV file for every user.

Try this:

Get-Content -Path "c:\users-input.txt" | %{ Get-ADUser -Filter {EmailAddress -eq $_} } | Select-Object SamAccountName | Export-CSV -Path "c:\users.csv"

Upvotes: 4

Related Questions