locked
Get-AdUser via EmailAddress then output SamAccountName to $Variable RRS feed

  • Question

  • Hi all,

    I'm creating a script to read email addresses from a CSV, match them to an AD Account, grab the SamAccountName of said AD account then do various things to that AD Account.

    So far I have (for the CSV Variables):

    $csv | ForEach-Object {
    
    $Surname = $_.Surname
    $Firstname = $_.Firstname
    $Email = $_.Email
    $EmailMatch = Get-ADUser -Filter EmailAddress -eq '$Email'

    $EmailMatch returns the details of the AD user in the first row of the csv based on the email address - which is exactly what I want - but I then want to get that users SamAccountName and pipe it to a variable so I can use it in the script.

    I've tried:

    $EmailMatch = Get-ADUser -Filter EmailAddress -eq '$Email' | Select -ExpandProperty SamAccountName

    But that just gives me the same output, and I'm not sure how to output it to a variable (or if that's even possible?) - I've googled and googled but can't seem to wrap my head around what I need to do and am feeling a little burnt out! I've not done much piping in Powershell yet.

    Any help?

    Many thanks


    Wednesday, July 11, 2018 1:15 PM

All replies

  • It seems that the variable $EmailMatch has exactly what you want. You can use that in another PowerShell statement, no need to pipe. Or perhaps:

    Get-ADUser -Filter EmailAddress -eq '$Email' | <some other statement, using $_.sAMAccountName to refer to the address>


    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Wednesday, July 11, 2018 3:07 PM