0

I have a simple script below I was looking at, but I cant understand why the writer includes the following "$($_.samAccountName)" I have tried the script with just $_.samAccountName and it works fine. Hopefully its an easy answer but why would you have the extra $() in the code?

Many thanks.

Get-ADGroup -Filter * |

foreach {

$props = [ordered] @{

GroupName = $_.Name

MemberCount = Get-ADGroupMember -Identity "$($_.samAccountName)" | Measure-Object |   select -ExpandProperty Count

}

New-Object -TypeName psobject -Property $props

} | sort MemberCount 

2 Answers 2

5

PowerShell does not evaluate object properties inside strings. If you have an expression like this:

"$_.samAccountName"

the variable (in this case the "current object" variable $_) is expanded to the return value of its ToString() method, while the remainder of the string (.samAccountName) remains unchanged. As a result you get something like this:

"CN=Domain Users,CN=Users,DC=example,DC=com.samAccountName"

instead of the value of the group object's samAccountName property.

Using the subexpression operator $() within the string

"$($_.samAccountName)"

forces PowerShell to evaluate the object's property and put the result in the string.

Example:

PS C:\> $g = Get-ADGroup 'Domain Users'
PS C:\> $g

DistinguishedName : CN=Domain Users,CN=Users,DC=example,DC=com
GroupCategory     : Security
GroupScope        : Global
Name              : Domain Users
ObjectClass       : group
ObjectGUID        : 072d9eda-a274-42ee-a4ee-b4c2810bb473
SamAccountName    : Domain Users
SID               : S-1-5-21-1227823062-450780232-214340840-513

PS C:\> $g.ToString()
CN=Domain Users,CN=Users,DC=example,DC=com
PS C:\> "$g"
CN=Domain Users,CN=Users,DC=example,DC=com
PS C:\> "$g.samAccountName"
CN=Domain Users,CN=Users,DC=example,DC=com.samAccountName
PS C:\> "$($g.samAccountName)"
Domain Users

However, as C.B. correctly said, in your particular case you don't need to enclose $_.samAccountName in double quotes at all. Using it like this:

$MemberCount = Get-ADGroupMember -Identity $_.samAccountName | ...

should work just fine.

Sign up to request clarification or add additional context in comments.

1 Comment

Ansgar Wiechers, thank you for a really good explanation. That is extremely helpful, cheers for taking the time to post that.
1

IMO there's no reason to use the variable/expression expansion syntax in this case.

Maybe the original writer, enclosing the value of -Identity parameter in double quotes, wants to be sure for the variable expansion.

2 Comments

Variable expansion is explained in this article.
Thanks both, that explains things. The article is great cheers vonPryz.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.