Powershell script - get AD -Propeties * based on either username OR e-mail address

Hello guys. I am new to PowerShell. I am trying to create a script that gets a CVS file with an emails list and a Username list, then obtain the properties emailaddress, title | select name,emailaddress, title

Do you think this will work like that, See below :

Thank you

Get-Content -Path C:\psscripts\somefilename.txt | ForEach-Object {

$UserDN = $null
$TargetOU = $Null
$Server= $null

If ($.UserName) {
# Username has a value
$UserDNxxx = (Get-ADUser - Server xxx -identity $
.UserName ) -properties *

} elseif ($.Email) {
# Email has a value
$UserDNxxx = (Get-ADUser -Server xxx -Filter {mail -eq $
.Email}).-properties *
} else {
# It doesn’t have either, so throw an error if you want
}

} | Export-csv -Path c:\psscripts\Adoutput.csv -NoTypeInformation

Best regards,

Edward

edward,
Welcome to the forum. :wave:t4:

Hmmm … why don’t you try it? :man_shrugging:t4:

Since you’re only using Get cmdlets it is nearly impossible to break something. :wink: And by running your code in the ISE oder in VSCode line by line you check each individual line or script block if it works or not. :+1:t4: That’s how we all do it - it’s called developing or debugging. :wink:

Regardless of that: When you carefully review your own question here you will notice that the forum software messed up your code a little bit. :point_up_2:t4:

Please … When you post code, sample data, console output or error messages format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in PowerShell.org <---- Click :point_up_2:t4: :wink:

Hello olaf

I know that but can you tell if the code looks correctly for you so far ? I don’t have PowerShell yet installed

If you have a Windows computer it is there by default. If you have a Linux or Mac system it takes about 2 Minutes to install it. :wink: It does not make any sense to write code without the abitlity to run it. :man_shrugging:t4:

I can. And it does not. But I think you wouldn’t learn something when I debug all your errors. :wink:

1 Like

Again … :point_up_2:t4: :point_up_2:t4: :point_up_2:t4: When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in PowerShell.org <---- Click :point_up_2:t4: :wink:

Please go back, edit your existing posts and fix the formatting of your code and error messages.

(post deleted by author)

I getting this error now

$.UserName : The term '$.UserName' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path 
was included, verify that the path is correct and try again.
At line:7 char:5
+ If ($.UserName) {
+     ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ($.UserName:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 
$.UserName : The term '$.UserName' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path 
was included, verify that the path is correct and try again.
At line:7 char:5
+ If ($.UserName) {
+     ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ($.UserName:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I am running this script below:

$UserDN = $null

$TargetOU = $Null

$Server= $null



If ($.UserName) {



# Username has a value



$UserDN= Get-ADUser -Server xxx -Filter {mail -eq $Email}-properties EmailAddress | Select-Object -ExpandProperty SamAccountName,Name,GivenName,EmailAddress, lastLogon



} elseif ($.Email) {

# Email has a value

$UserDN= (Get-ADUser -Server xxx -Identity $_.UserName).distinguishedName





} else {

# It doesn’t have either, so throw an error if you want

}



} | Export-csv C:\Users\emo3677\Documents\AD\Adoutput.csv -NoTypeInformation

And getting this error below :





$.UserName : The term '$.UserName' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path

was included, verify that the path is correct and try again.

At line:7 char:5

+ If ($.UserName) {

+ ~~~~~~~~~~

+ CategoryInfo : ObjectNotFound: ($.UserName:String) [], CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

$.UserName : The term '$.UserName' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path

was included, verify that the path is correct and try again.

At line:7 char:5

+ If ($.UserName) {

+ ~~~~~~~~~~

+ CategoryInfo : ObjectNotFound: ($.UserName:String) [], CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException


Any suggestion ?

Hello I am running this

$UserDN = $null
$TargetOU = $Null
$Server= $null

If ($.UserName) {

# Username has a value

$UserDN= Get-ADUser -Server  xxx -Filter {mail -eq $Email}-properties EmailAddress | Select-Object -ExpandProperty SamAccountName,Name,GivenName,EmailAddress, lastLogon

} elseif ($.Email) {
# Email has a value
$UserDN= (Get-ADUser -Server xxx -Identity $_.UserName).distinguishedName


} else {
# It doesn’t have either, so throw an error if you want
}

} | Export-csv C:\Users\emo3677\Documents\AD\Adoutput.csv -NoTypeInformation

I am getting this error here, any help?

$.UserName : The term '$.UserName' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path 
was included, verify that the path is correct and try again.
At line:7 char:5
+ If ($.UserName) {
+     ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ($.UserName:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 
$.UserName : The term '$.UserName' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path 
was included, verify that the path is correct and try again.
At line:7 char:5
+ If ($.UserName) {
+     ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ($.UserName:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I merged your different posts because they are all about the same issue.

If that’s really your code you should URGENTLY make a BIG step back and start with learning the very fundamentals of PowerShell first. This will save you from a lot of wasted time and frustrations. And it will enable you to understand the help you get in forums like this.

I’d expect that there is code missing before the code you shared. If you have a plain text file as input you don’t have properties like UserName in your pipeline variable. And the pipeline variable is $_ instead of $.
Assumed you have a proper CSV file with the columns UserName and Email you should start with something like this:

$Result = 
Import-Csv -Path 'C:\psscripts\UserList.csv' |
    ForEach-Object {
        if ($_.UserName) {
            Get-ADUser -Identity $_.UserName
        }
        elseif ($_.Email) {
            $Email = $_.Email
            Get-ADUser -Filter "mail -eq '$Email'"
        }
        else {
            $ErrorList += $_
        }
    }
$Result
$Result | 
    Export-csv -Path 'c:\psscripts\Adoutput.csv' -NoTypeInformation
$ErrorList

Try to understand what it does and modify it to your needs.

Thank you very much, Olaf, I debugged and ran it and it works, however, when it gave an error when it does not contain the Username and it does not look by Email how we can fit that? another question I have is how I can look at multiple servers For instance: Server1, Server 2, Server 3, Server 4 any given server

$Result = 

Import-Csv -Path C:\Users\emo3677\Documents\AD\somefilename.csv |


    ForEach-Object {


        if ($_.UserName) {

          # Username has a value


        Get-ADUser -Server xx1 Identity $_.UserName -Properties *


        }


        elseif ($_.Email) {
        
            $Email = $_.Email

  Get-ADUser -Server Sever 1, Server 1 -Filter {mail -eq $Email}-properties EmailAddress | Select-Object -ExpandProperty SamAccountName,Name,GivenName,EmailAddress, lastLogon
        
        }


        else {
            $ErrorList =+ $_
        }
    }
$Result
$Result|

    Export-csv C:\Users\emo3677\Documents\AD\Adoutput.csv -NoTypeInformation
$ErrorList


Thanks in advance
edd

It depends in what attribute the email is saved. Usually it is mail - it might be EmailAddress for y. You may check it by outputting all attributes of a given user with …

Get-ADUser -Identity '<sAMAccountName>' -Properties * 

Now you inspect the output for the desired email address and use the attribute name in your filter value.
BTW: The value type for the parameter -Filter is a string - not a scriptblock! :wink:

Don’t you get errors when you provide more than one server? If you have only one single domain you don’t need to query each individual server. If you have multiple domains you need a loop to search in all of them.

You should learn how to read the help to understand the syntax of the cmdlets you’re using.

And please … when you post code try to avoid posting that much useless whitespace. It makes your code much harder to read.
Here you may read more about good style

BTW: What do you use for developing? I’d recommend using VSCode.