Author Posts

April 27, 2018 at 3:39 pm

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

April 27, 2018 at 4:16 pm

$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

April 27, 2018 at 4:20 pm

Worked like a charm! Thank you!