Retro69
Retro69

Reputation: 57

A Simple Powershell Script. Why the extra "$()" in code?

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 

Upvotes: 0

Views: 217

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

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.

Upvotes: 5

CB.
CB.

Reputation: 60910

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.

Upvotes: 1

Related Questions