Reputation: 2531
I was noticing some odd behavior in PowerShell. I have verified what I believe is erroneous behavior in both PowerShell 2 and PowerShell 4. Is it truly a bug or is it just something I'm doing wrong?
Take the following snippet. The idea is to simply iterate through a list (string array) of Active Directory group names, and tell me how many members are in each group:
Foreach($ADGroupName In [String[]]'Domain Admins', `
'Enterprise Admins', `
'Administrators', `
'Account Operators', `
'Backup Operators')
{
$Group = Get-ADGroup -Filter { Name -EQ $ADGroupName } -Properties Members
If ($Group -EQ $Null -OR $Group.PropertyNames -NotContains 'Members')
{
# This only happens on the first iteration of the loop!
Write-Error "$ADGroupName was null or was missing the Members property!"
}
Else
{
Write-Host "$ADGroupName contains $($Group.Members.Count) members."
}
}
On the first iteration through the loop, I get the error because $Group is $null and therefore contains no Members properly, although the command and the group name are both valid and the group has members. Subsequent iterations through the loop work fine. But it does not matter what the first group in the list is. I can reorder the group, but it always returns the error on the first element of the string array.
To work around it for now, I've simply included a 'DummyGroup' as the first element of the array, and handle the expected exception gracefully, then every other group in the list works fine.
Is there a better way of dealing with what appears to be a bug?
Upvotes: 2
Views: 537
Reputation: 28963
As mjolinor fixed that error; just for the fun of practicing PowerShell, I rewrote it a bit, removing the bug-error-check.
@()
to make the array of group names, with no need for the backtick line continuation.Get-ADGroup $ADGroupName -Properties Members
with no need for a filtere.g.
$ADGroupNames = @('Domain Admins',
'Enterprise Admins',
'Administrators',
'Account Operators',
'Backup Operators')
$ADGroups = $ADGroupNames | Get-ADGroup -Properties Members
$ADGroups | ForEach { write "$($_.Name) contains $($_.Members.Count) members" }
Upvotes: 1
Reputation: 68243
Don't know if you'd really call it a "bug" or not, but it's caused by using a variable in a script block filter. If you change to using a string filter with an expandable string, the variable expansions work as expected:
Foreach($ADGroupName In [String[]]'Domain Admins', `
'Enterprise Admins', `
'Administrators', `
'Account Operators', `
'Backup Operators')
{
$Group = Get-ADGroup -Filter "Name -EQ '$ADGroupName'" -Properties Members
If ($Group -EQ $Null -OR $Group.PropertyNames -NotContains 'Members')
{
# This only happens on the first iteration of the loop!
Write-Error "$ADGroupName was null or was missing the Members property!"
}
Else
{
Write-Host "$ADGroupName contains $($Group.Members.Count) members."
}
}
Upvotes: 3