Get-ADUser with Get-Content

So i have a task to perform. i have a list of AD Users on a sheet. Column A has first name and Column B has last name. Whats the best method of using the Get-AdUser command to match the first name and last name of the user to the AD Object then Give me the SamAccountName of the object? Also if possible spit out an error log if it could not find that user or if there are duplicates? Please help. Thank you. 

Parents
  • A suggested answer is at the end of this post. If you choose not to take the TL;DR approach.

    As for this ---

    So i have a task to perform. i have a list of AD Users on a sheet. Column A has first name and Column B has last name.

    Answer: This is fine

    ---


    As for this ---

    Whats the best method of using the Get-AdUser command to match the first name and last name of the user to the AD Object then Give me the SamAccountName of the object?

    Answer: Just combine Col A and B and match that to the AD display name to get the SamAccountName.

    ---


    As for this ---

    Also, if possible, spit out an error log if it could not find that user or if there are duplicates?

    Answer: You have to code for error trapping based on what you are looking for.

    ---

    So, stepping thru each of the above, seems to indicate that you are never really fully used PowerShell, or very new to PowerShell, especially regarding AD. So, it is vital that you get ramped on it, to limit / eliminate, issues, concerns, misconceptions, frustrations, and potential major damage that can be caused if you are doing something you are unsure of, using someone else’s code (no matter where you get it from) and running it without truly understanding what it does. I say this because, what you are asking is a PowerShell 100 level question, something that is done every day, and there literally tons of examples all over the web on how to do this, even pre-written scripts that you could use as is, or tweak as needed. There are also tools built in to Windows ADDS that will write the base code for you and you can then tweak as needed. There are several examples in the PowerShell help files on your host and online.

    For example:

    Introduction to Active Directory Administrative Center Enhancements (Level 100)
    https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/get-started/adac/introduction-to-active-directory-administrative-center-enhancements--level-100-


    Learning PowerShell with Active Directory Administrative Center (PowerShell History Viewer)
    https://sid-500.com/2017/10/10/learning-powershell-with-active-directory-administrative-center-powershell-history-viewer


    Step-By-Step: Utilizing PowerShell History Viewer in Windows Server 2012 R2
    https://blogs.technet.microsoft.com/canitpro/2015/03/04/step-by-step-utilizing-powershell-history-viewer-in-windows-server-2012-r2


    Use Active Directory Administrative Center to Create PowerShell Commands in Windows Server 2012
    https://www.petri.com/use-active-directory-administrative-center-create-powershell-commands


    That being said, see my reddit post for learning this stuff.
    https://www.reddit.com/r/PowerShell/comments/bserj9/learn_powershell/eooduq9/?context=3
    https://www.reddit.com/r/PowerShell/comments/bserj9/learn_powershell/eoodxzu/?context=3

    So, in short, relative to your use case.

    Read in the file using:
    Import-Csv, not get content, since this is already columnar / table-based file. Hopefully, you have headers (which become properly names) on the file, and if not, that cmdlet allows for creating them on import.

    On the read, just combine the two columns as a single variable and use that to match the AD User display name and select the SamAccountName

    There will never be duplicate user names in ADDS. Names must be unique. If you are saying there may be duplicate names in your import file, then correct that first, so you don’t have to deal with such things.

    Error message happen by default. There are different types of errors, mostly these are terminating and non-terminating errors caused by code, or environment. You must decide how to handle each. You can get a log automatically for you process simply by using the transcript cmdlets.

    Start-Transcript
    Stop-Transcript

    So, something as simple after looking at the help files / examples for the aforementioned cmdlets:


    Start-Transcript -Path '.\ADUserCheckReport.txt'
    Import-Csv -Path 'C:\Temp\ADUserLIst.csv' |
    ForEach {
        "Processing $PSitem"
         (Get-ADUser -Filter "DisplayName -eq '$($PSItem.FirstName) $($PSItem.LastName)'").SamAccountName
    }
    Stop-Transcript

  • thanks for the help. 

    I am getting this error. 

    Import-Csv -Path 'C:\Scripts\users.csv' |
    ForEach {
    "Processing $PSitem"
    (Get-ADUser -Filter "EmailAddress -eq '$($PSItem.EmailAddress)'").SamAccountName
    } | Export-Csv -Path C:\Scripts\export.csv -NoTypeInformation
    Export-Csv : Cannot bind argument to parameter 'InputObject' because it is
    null.
    At line:5 char:5
    + } | Export-Csv -Path C:\Scripts\export.csv -NoTypeInformation
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidData: (:) [Export-Csv], ParameterBindingV
    alidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M
    icrosoft.PowerShell.Commands.ExportCsvCommand

    I changed your script to reflect this: 

    Import-Csv -Path 'C:\Scripts\users.csv' |
    ForEach {
    "Processing $PSitem"
    (Get-ADUser -Filter "EmailAddress -eq '$($PSItem.EmailAddress)'").SamAccountName
    } | Export-Csv -Path C:\Scripts\export.csv -NoTypeInformation

    My CSV file only contains one header called "emailaddress"

    And im trying to translate over 600 email addresses to the users samaccountname

  • You did not say in your original post that you wanted to export this to a file.

    So, FYI, when you post to Q&A site, you must provide all of what you've tried, done, errors, input and expected output, or you leave people to guess, and end up in far longer threads then needed.

    This error ...

    Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null.

    ... specifically, says, that nothing is coming back from your Csv file or your code.

    How is this 'EmailAddress' shown in the file?
    Meaning, emailaddres or
    emailaddress@domain.com?

    You need to be specific for what you ask for (in your file or in your code), PowerShell will not try an figure it out for you.


    As for this ...

    And im trying to translate over 600 email addresses to the users samaccountname

    ... I don't understand what you mean by it.

    The default for ADDS and Exchange is that the user default SamAccountName, is there email alias. So, they are the same by default.
    If you run ...

    Get-Mailbox

    ... on your Exchange server (or via an implicit / explicit PowerShell Remoing session), you see that name in the ALias property.
    Unless your ADDS folks are doing something unique, there should be no need for 'translation' of any sort.
    ALso, by default, the UPN is the users email address.

    Lastly, not all properties are returned using the default cmdlet, there will be cases where you must specifically ask to see and use it. For example:


    # Get the first user fromm AD and look at the default properties returned.
    (Get-ADUser -Filter *)[0] | Get-Member

    <#
       TypeName: Microsoft.ActiveDirectory.Management.ADUser

    Name              MemberType            Definition                                                                                                                    
    ----              ----------            ----------                                                                                                                    
    Contains          Method                bool Contains(string propertyName)                                                                                            
    Equals            Method                bool Equals(System.Object obj)                                                                                                
    GetEnumerator     Method                System.Collections.IDictionaryEnumerator GetEnumerator()                                                                      
    GetHashCode       Method                int GetHashCode()                                                                                                             
    GetType           Method                type GetType()                                                                                                                
    ToString          Method                string ToString()                                                                                                             
    Item              ParameterizedProperty Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Item(string propertyName) {get;}                               
    DistinguishedName Property              System.String DistinguishedName {get;set;}                                                                                    
    Enabled           Property              System.Boolean Enabled {get;set;}                                                                                             
    GivenName         Property              System.String GivenName {get;set;}                                                                                            
    Name              Property              System.String Name {get;}                                                                                                     
    ObjectClass       Property              System.String ObjectClass {get;set;}                                                                                          
    ObjectGUID        Property              System.Nullable`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] ObjectGUID {ge...
    SamAccountName    Property              System.String SamAccountName {get;set;}                                                                                       
    SID               Property              System.Security.Principal.SecurityIdentifier SID {get;set;}                                                                   
    Surname           Property              System.String Surname {get;set;}                                                                                              
    UserPrincipalName Property              System.String UserPrincipalName {get;set;}                                                                                    
    #>

    # Get the first user from AD and look at the default and additional properties returned.
    (Get-ADUser -Filter '*' -Properties emailaddress)[0] | Get-Member
    <#
       TypeName: Microsoft.ActiveDirectory.Management.ADUser

    Name              MemberType            Definition                                                                                                                    
    ----              ----------            ----------                                                                                                                    
    Contains          Method                bool Contains(string propertyName)                                                                                            
    Equals            Method                bool Equals(System.Object obj)                                                                                                
    GetEnumerator     Method                System.Collections.IDictionaryEnumerator GetEnumerator()                                                                      
    GetHashCode       Method                int GetHashCode()                                                                                                             
    GetType           Method                type GetType()                                                                                                                
    ToString          Method                string ToString()                                                                                                             
    Item              ParameterizedProperty Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Item(string propertyName) {get;}                               
    DistinguishedName Property              System.String DistinguishedName {get;set;}                                                                                    
    EmailAddress      Property              System.String EmailAddress {get;set;}                                                                                         
    Enabled           Property              System.Boolean Enabled {get;set;}                                                                                             
    GivenName         Property              System.String GivenName {get;set;}                                                                                            
    Name              Property              System.String Name {get;}                                                                                                     
    ObjectClass       Property              System.String ObjectClass {get;set;}                                                                                          
    ObjectGUID        Property              System.Nullable`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] ObjectGUID {ge...
    SamAccountName    Property              System.String SamAccountName {get;set;}                                                                                       
    SID               Property              System.Security.Principal.SecurityIdentifier SID {get;set;}                                                                   
    Surname           Property              System.String Surname {get;set;}                                                                                              
    UserPrincipalName Property              System.String UserPrincipalName {get;set;}                                                                                    
    #>


    # Get the first user from AD and look at the all properties returned.
    (Get-ADUser -Filter '*' -Properties '*' )[0] | Get-Member
    <#
       TypeName: Microsoft.ActiveDirectory.Management.ADUser

    Name                                 MemberType            Definition                                                                                                 
    ----                                 ----------            ----------                                                                                                 
    ...
    Department                           Property              System.String Department {get;set;}                                                                        
    Description                          Property              System.String Description {get;set;}                                                                       
    directReports                        Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection directReports {get;}                        
    DisplayName                          Property              System.String DisplayName {get;set;}                                                                       
    DistinguishedName                    Property              System.String DistinguishedName {get;set;}                                                                 
    Division                             Property              System.String Division {get;set;}                                                                          
    DoesNotRequirePreAuth                Property              System.Boolean DoesNotRequirePreAuth {get;set;}                                                            
    dSCorePropagationData                Property              Microsoft.ActiveDirectory.Management.ADPropertyValueCollection dSCorePropagationData {get;}                
    EmailAddress                         Property              System.String EmailAddress {get;set;}                                                                      
    EmployeeID                           Property              System.String EmployeeID {get;set;}                                                                        
    EmployeeNumber                       Property              System.String EmployeeNumber {get;set;}                                                                    
    Enabled                              Property              System.Boolean Enabled {get;set;}                                                                          
    ...
    mail                                 Property              System.String mail {get;set;}                                                                              
    mailNickname                         Property              System.String mailNickname {get;set;}                                                                      
    ...
    SamAccountName                       Property              System.String SamAccountName {get;set;}                                                                    
    ....
    #>


    If your files' email column is this way ... emailaddress@domain.com then this should work as expected.

    Import-Csv -Path 'C:\Temp\ADUserLIst.csv' |
    ForEach {
        "Processing $PSitem"
         (Get-ADUser -Filter "EmailAddress -eq '$($PSItem.emailaddress)'").SamAccountName
    }


    If you files email column is this way ... emailaddress then you have to add the domain name in code, because that is not an email address, it is a user/email alias name.
    It's easier just to fix this in the file, or you end up with stuff like this...

    Import-Csv -Path 'C:\Temp\ADUserLIst.csv' |
    ForEach {
        "Processing $PSitem"
         (Get-ADUser -Filter "EmailAddress -eq '$($PSItem.emailaddress + "@$env:USERDNSDOMAIN")'").SamAccountName
    }

    Sure, it works, but, well, you know.

    FYI...

    I know each f what I provided works, because I did them in one of my labs as part of the response.

    As far as the export is concerned, it's only one column, so, no real need for Export -Csv use, since there is noting to comma separate. Also, you have that command in the wrong place, as you want to write to the file as each record is processed inside the ForLoop,, so each record is written, not after it is done.

    Import-Csv -Path 'C:\Temp\ADUserLIst.csv' |
    ForEach {
         (Get-ADUser -Filter "EmailAddress -eq '$($PSItem.emailaddress)'").SamAccountName |
         Out-File -FilePath 'c:\temp\UserEmailReport.txt' -Append
    }

    If you want to do it after, then you have to collect all that first, then output.

    $UserEmailArray = @()
    Import-Csv -Path 'C:\Temp\ADUserLIst.csv' |
    ForEach {
         $UserEmailArray += $((Get-ADUser -Filter "EmailAddress -eq '$($PSItem.emailaddress)'").SamAccountName  )
    }
    $UserEmailArray | Out-File -FilePath 'c:\temp\UserEmailReport.txt'

    https://powershellexplained.com/2018-10-15-Powershell-arrays-Everything-you-wanted-to-know

Reply Children
No Data