Get-ADUser from Array

This topic contains 2 replies, has 2 voices, and was last updated by  Joel R 3 weeks, 4 days ago.

  • Author
    Posts
  • #99874

    Joel R
    Participant

    Hello all,
    Trying to get specific details of users in a group using Powershell. The code I'm using is:

    # Define variables
    $adGroupMembers = @()
    $adGroupMembersDetails = @()
    $adGroupName = read-host "Please Enter Group Name"
    
    #Get group members
    $adGroupMembers = Get-ADGroupMember $adGroupName | Select SamAccountName
    
    ForEach ($groupMember in $adGroupMembers) {
    	$groupMember
    	Get-ADUser $groupMember -Properties SamAccountName,Surname,GivenName,Mail,Enabled | Select SamAccountName,Surname,GivenName,Mail,Enabled | Export-CSV "C:\PowerShellScripts\Output\AD_User_Info.csv" -Append -notypeinformation
    	}
    

    The error I receive is:
    Get-ADUser : Cannot find an object with identity: 'samaccountname -eq '@{SamAccountName=SAMACCOUNTNAME}' under:
    'DC=cs,DC=DOMAINNAME,DC=com'.
    At C:\PowerShellScripts\Scripts\GetGroupMembers.ps1:12 char:2
    + Get-ADUser $filterstring # -Properties SamAccountName,Surname,Giv ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (samaccountname ...tName=SAMACCOUNTNAME}:ADUser) [Get-ADUser], ADIdentityNotFo
    undException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
    icrosoft.ActiveDirectory.Management.Commands.GetADUser

    The last part works fine if pulling from a text file or a .csv, but not if it's pulling from an array. I've read posts where Get-ADUser can't pull from an array, but once it's in a ForEach, it's referencing a single variable pulled from the array, not the entire array, correct?

    Thanks in advance for any help.
    JR

  • #99877

    Joel Sallow
    Participant
    $adGroupMembers = Get-ADGroupMember $adGroupName | Select SamAccountName

    Here's your issue. So, by default, Select-Object keeps the properties in an object, even if you have only one. Add the -ExpandProperty (or just -Expand for short) parameter to have it pull the actual string out so you can use it directly:

    $adGroupMembers = Get-ADGroupMember $adGroupName | Select-Object -ExpandProperty SamAccountName
  • #99879

    Joel R
    Participant

    Worked like a charm! Thank you!

You must be logged in to reply to this topic.