Powershell - if computer is a member of group then...

Pete
Pete used Ask the Experts™
on
What's the easiest way to write:

Get-adgroupmember -identity "whatever"
If the computer name I'm running the script on is in this list then
{
Run something
}



Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Bradley FoxLAN/WAN Systems Administrator
Commented:
One Liner
Get-ADGroupMember GroupName | foreach  {if ($_.name -eq $env:computername) {Do Something Here}}

Open in new window


Script Format
$groupMembers = Get-ADGroupMember GroupName
foreach ($member in $groupMembers)
           { If ($member.name -eq $env:computername)
                   { do something here
                   }
           }

Open in new window

PowerShell Developer
Top Expert 2010
Commented:
The efficient way.
$dn = Get-ADComputer -Identity $env:COMPUTERNAME | Select-Object -ExpandProperty DistinguishedName
if ($group = Get-ADGroup -Filter { name -eq 'The group' -and member -eq $dn }) {
    Write-Host "$env:COMPUTERNAME is in $($group.Name)"
}

Open in new window

Marginally more code, but you only want to know about one group, and a group that contains the computer as a member.

Author

Commented:
Thanks to you both. I like the efficient way.

WIithout the first $dn line couldn't I just simplify:

if ($group = Get-ADGroup -Filter { name -eq 'The group' -and member -eq $env.COMPUTERNAME }) {
    Write-Host "$env:COMPUTERNAME is in $($group.Name)"
}
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Chris DentPowerShell Developer
Top Expert 2010

Commented:
No, the query for member must be a distinguished name.

Author

Commented:
A follow up, once written I need to run this on domain workstations as a startup script, but AFAIK the get-adgroup command will only be available if I install RSAT? I cant install this on end user workstations.

Thanks
Chris DentPowerShell Developer
Top Expert 2010

Commented:
Absolutely, no need though. This might need a little tweaking depending on PowerShell versions out on your shop-floor. It does the same thing as the original, using a slightly less friendly interface, one which is always present.

Please note the trailing $ in the search for the computer account is entirely intentional.
$dn = ([ADSISearcher]"(&(sAMAccountName=$env:COMPUTERNAME$))").FindOne().Properties['distinguishedName'][0]
if ($group = ([ADSISearcher]"(&(name=The Group)(member=$dn))").FindAll()) {
    Write-Host "$env:COMPUTERNAME is in $($group.Properties['name'][0])"
}

Open in new window

Author

Commented:
I am getting the error:
"Can not index into a null array"
Chris DentPowerShell Developer
Top Expert 2010

Commented:
Oops, sorry, FindAll...
$dn = ([ADSISearcher]"(&(sAMAccountName=$env:COMPUTERNAME$))").FindOne().Properties['distinguishedName'][0]
if ($groups = ([ADSISearcher]"(&(name=The Group)(member=$dn))").FindAll()) {
    foreach ($group in $groups) {
        Write-Host "$env:COMPUTERNAME is in $($group.Properties['name'][0])"
    }
}

Open in new window

It should be impossible for it to find more than one group with the same name. This is the "just in case" mode :)

Author

Commented:
Thanks, my test computer is in a group called 'Test Computer Group'. Yet running the script below gives no output..

---

$dn = ([ADSISearcher]"(&(sAMAccountName=$env:COMPUTERNAME$))").FindOne().Properties['distinguishedName'][0]
if ($groups = ([ADSISearcher]"(&(name='Test Computer Group')(member=$dn))").FindAll()) {
    foreach ($group in $groups) {
        Write-Host "$env:COMPUTERNAME is in $($group.Properties['name'][0])"
    }
}
Chris DentPowerShell Developer
Top Expert 2010

Commented:
The quotes you've added are breaking it. No quotes inside the LDAP filter (or it treats them as literal. Added an extra filter term as well.
$dn = ([ADSISearcher]"(&(sAMAccountName=$env:COMPUTERNAME$))").FindOne().Properties['distinguishedName'][0]
if ($groups = ([ADSISearcher]"(&(objectClass=group)(name=Test Computer Group)(member=$dn))").FindAll()) {
    foreach ($group in $groups) {
        Write-Host "$env:COMPUTERNAME is in $($group.Properties['name'][0])"
    }
}

Open in new window

Author

Commented:
Sorry but the computer I'm running this script on is in 'test computer group' but still no output, what am I doing wrong here?
Thanks
Bradley FoxLAN/WAN Systems Administrator

Commented:
Does this script need to run under the user's context?  If it can run under the computer's context then I suggest creating a group policy object, edit out all the group stuff and leave just the meat of the powershell script in tact and set it to run as a computer startup script in the GPO.  Edit the permissions on the GPO removing Authenticated Users group and add the Group you are testing for and set the permissions to read and apply group policy.

This will run the script on computers in that AD Group.  This would be the  most efficient way to run this script, assuming it does not need to run under the user's context.
Chris DentPowerShell Developer
Top Expert 2010

Commented:
It can run as either user or computer, as long as it can pick up the computer name. If environment variables are not available (for whatever reason) there are other ways.

I'm sorry I didn't update this today, it was on my to-do list and got left behind. I'll try and update it first thing tomorrow.
Bradley FoxLAN/WAN Systems Administrator

Commented:
If it can run computer I'd suggest using a GPO then.  Computer name can be grabbed using $env:computername in powershell.  The link below is a Microsoft article on this.  They are talking about logon scripts but it's exactly the same for a startup script, just configure it under the Computer Config node and link the GPO to the OU with the computers.  Make sure to edit the security of the GPO for the group of computers you want to run it on.

https://technet.microsoft.com/en-us/library/ee431705(v=ws.10).aspx
Chris DentPowerShell Developer
Top Expert 2010

Commented:
I've checked the sample properly now, and I can't find a problem. This means it's likely a problem of picking the right attributes.

This gets us the AD object for the current computer:
([ADSISearcher]"(&(sAMAccountName=$env:COMPUTERNAME$))").FindOne()

Open in new window

We can get the list of groups the computer belongs to by looking at the memberOf attribute.
([ADSISearcher]"(&(sAMAccountName=$env:COMPUTERNAME$))").FindOne().Properties['memberOf']

Open in new window

This should produce a list like this:
CN=Group 1,OU=Security Groups,DC=domain,DC=ads
CN=Group 2,OU=Security Groups,DC=domain,DC=ads

Open in new window

The value we're basing the query on at the moment is what falls after the first "CN=". So I might use the query like this:
$dn = ([ADSISearcher]"(&(sAMAccountName=$env:COMPUTERNAME$))").FindOne().Properties['distinguishedName'][0]
if ($groups = ([ADSISearcher]"(&(objectClass=group)(name=Group 1)(member=$dn))").FindAll()) {
    foreach ($group in $groups) {
        Write-Host "$env:COMPUTERNAME is in $($group.Properties['name'][0])"
    }
}

Open in new window

The distinction is important because group objects have more than one name, they also use displayName and sAMAccountName.

Does that get you any further?

By the way, I don't disagree with the recommendation that you use security filtering for a GPO. But I'd like to leave this as a somewhat complete example in case the GPO approach doesn't suit your needs.

Author

Commented:
Thanks Chris and others, it is now working, we had a path and execution policy problem, not a problem with your script.

I decided on powershell method for this due to a previous disaster where we tried to use item level targeting to push out printers based on computer group. I kind of felt like this, although sound theoretically, it may produce the same erratic behaviour. Maybe permissions will work perfectly...next time.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial