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

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
LVL 1
PeteAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mcsweenSr. Network AdministratorCommented:
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

0
Chris DentPowerShell DeveloperCommented:
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.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
PeteAuthor 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)"
}
0
Discover the Answer to Productive IT

Discover app within WatchGuard's Wi-Fi Cloud helps you optimize W-Fi user experience with the most complete set of visibility, troubleshooting, and network health features. Quickly pinpointing network problems will lead to more happy users and most importantly, productive IT.

Chris DentPowerShell DeveloperCommented:
No, the query for member must be a distinguished name.
0
PeteAuthor 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
0
Chris DentPowerShell DeveloperCommented:
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

0
PeteAuthor Commented:
I am getting the error:
"Can not index into a null array"
0
Chris DentPowerShell DeveloperCommented:
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 :)
0
PeteAuthor 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])"
    }
}
0
Chris DentPowerShell DeveloperCommented:
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

0
PeteAuthor 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
0
mcsweenSr. Network AdministratorCommented:
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.
0
Chris DentPowerShell DeveloperCommented:
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.
0
mcsweenSr. Network AdministratorCommented:
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
0
Chris DentPowerShell DeveloperCommented:
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.
0
PeteAuthor 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.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.