Trouble with Get-Aduser from CSV

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 1 year, 4 months ago.

  • Author
    Posts
  • #29171
    Profile photo of Michael Arnold
    Michael Arnold
    Participant

    Trying to Get-Aduser based on description. I have a csv with a list of serial numbers. These are added to the description field of Ad users. When I run my code nothing returns.
    CSV:
    Description
    5CD50801ZC
    98VGJ42
    J8TFJ42
    6NVFJ42
    7PQFJ42
    1GTFJ42

    
    
    Code:
    `
    $csv = Import-Csv C:\scripting\chromebook1.csv 
    
    foreach ($line in $csv)
    {get-aduser -Filter {description -like $line} -SearchBase 'OU=LEADERSHIP,DC=DS,DC=NET'}
    `
    
    
  • #29174
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Two things here: One, the -Like operator requires some wildcards, if you're planning to look for a string that contains something else. Also, you need to be looking at $line.Description, rather than just $line. Try this:

    $csv = Import-Csv C:\scripting\chromebook1.csv 
    
    foreach ($line in $csv)
    {
        get-aduser -Filter "description -like '*$($line.Description)*'" -SearchBase 'OU=LEADERSHIP,DC=DS,DC=NET'
    }
    
    

    I've changed your -Filter argument from a script block literal to a double-quoted string, based on past experience with the AD cmdlets where sometimes the script block syntax doesn't work the way you expect it to.

  • #29175
    Profile photo of Michael Arnold
    Michael Arnold
    Participant

    That work, thanks!

    Question, why is the "$" required outside of the ($line.description)?

  • #29176
    Profile photo of Michael Arnold
    Michael Arnold
    Participant

    .

  • #29177
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    That's a sub-expression operator, and is what you use in strings when you want to expand something more complex than just a simple variable name. Otherwise, $line would get expanded, and the text ".Description" would become a literal part of the string, which is not what we want.

You must be logged in to reply to this topic.