1
votes

I am new to powershell, but actually I need a script so I started to read myself into this stuff and found powershell.

I have a username list like:

  • xyxz
  • domainname\xyxz.xyxc

This script should search all the samaccountname from my userlist and give me the email adresses for every samaccountname.

Get-Content C:\Users\xxxxx\Desktop\Users.txt | forEach { Get-ADUser "I dont Know how to specify the username" | select mail | Export-Csv output.csv }

This is the script I was writing know, but I don't know how to finish it to get it work. I know it is not well done but I don't wanted to write some text here without doing something myself.

2

2 Answers

4
votes

You were kind of close

Get-Content C:\Users\xxxxx\Desktop\Users.txt | forEach { Get-ADUser $_ -properties EmailAddress} | select -ExpandProperty EmailAddress | Out-File output.csv 

should do the trick (if your txt file contains the samid, and only one per line).

You can access objects inside the pipeline by using $_. Also to get the String value of a property with select you have to use -ExpandProperty.

In this case you also have to select the property (EmailAddress) specifically since only a limited set of properties is reported back by default to reduce workload (this is done by specifying the -properties Parameter.

2
votes

Your command is about right. However, Get-ADUser doesn't seem to accept usernames in the UPN or Down-Level Logon Name formats.
To query a domain other than the one the current user is logged on, you need to use the -Server option. This option accepts either FQDN or NetBIOS domain names. Another thing: by default, Get-ADUser returns only the default properties set (see this list to know the default properties), and a user's email address is not a default property, so we need to use the -Properties option to add it to the returned values.

The command would look like this:

$defaultDomain = $env:USERDOMAIN
$usersFilePath = C:\Users\xxxxx\Desktop\Users.txt
Get-Content $usersFilePath | %{
    if ($_.Contains("\")) {
    @{username = $_.Split("\")[1]; server = $_.Split("\")[0]}
    } 
    elseif ($_.Contains("@")) {
        @{username = $_.Split("@")[0]; server = $_.Split("@")[1]}
    }
    else {
        @{username = $_; server = $defaultDomain}
    }
} | %{ Get-ADUser -Identity $_.username -Properties Mail -Server $_.server} | select -ExpandProperty mail