Home > OS >  How Can I Make A ForLoop in Windows and Insert with Single Quotes Around the For-Each Operator
How Can I Make A ForLoop in Windows and Insert with Single Quotes Around the For-Each Operator

Time:05-20

So I have a weird task, I am trying to clean up my AD Membership and I need to write a for-loop for the task. We have groups that are assigned to a group, and we are trying to remove the groups from groups as nest groups are not supported. I have a good for-loop that currently works:

Main Command:

Get-ADGroup -Filter * | Select-Object -Property Name

The above command gives me a list of all of the Domain Groups. I want to take this list and iterate over it showing me the group memebership.

With ForEach-Object Statement:

Get-ADGroup -Filter * | Select-Object -Property Name | ForEach-Object { Get-ADGroupMember -Identity $_}

This doesn't work, because I can't get the group_name string to be returned into the $_ with single quotes. Instead, I need to return a single quote around the $_ operator so that it returns the group_name in 'group_name'.

How can I get single quotes to return around the group_name?

CodePudding user response:

The issue with the statement:

Get-ADGroup -Filter * | Select-Object -Property Name | ForEach-Object { Get-ADGroupMember -Identity $_ }

Is that $_ refers to an object which's Property is Name and Get-ADGroupMember doesn't know how to deal with said object, if instead, you were referring to the Property Value of the object it should work correctly:

... | ForEach-Object { Get-ADGroupMember -Identity $_.Name }

It's important to note that, Select-Object in this case, is not needed at all and is only slowing your script down and furthermore, if you want to find all groups having a nested group as member you could use a filtering cmdlet such as Where-Object:

Get-ADGroup -Filter * | Where-Object {
    (Get-ADGroupMember $_.DistinguishedName).where({ $_.ObjectClass -eq 'group' }, 'First')
}
  • Related