Check user group membership in logonscript

Hi everybody,

FIrst post in here :slight_smile:

This might seem trivial but I have run out of patience :slight_smile:

I’m trying to set up a simple function in a logon script to check if the current user is a member of an AD group.
I must accomplish that without the ActiveDirectory module as this is not installed where the logon script runs.

I would like to test for nested groups as well.

It has to run under as a normal user with normal permissions.

I know I cannot be the first to want this but I have not been able to find the function.

Maybe I should say what my problem is :slight_smile:

I have ended up in the same place that Richard Siddaway in this blog post:

To add to this the code seems to work on a Windows 2012 R2 as an admin.

The code fails on Windows Server 2008 R2 for both normal and admin users as indicated by Richard

So way back when I was first trying to get in to PowerShell, one of the first things I tried to do was change the logon script from VBS to PowerShell. To handle the group memerbership, at least without recursion the following method seemed to work for us.

$username = $env:USERNAME
$adGroups = ((New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=User)(samAccountName=$env:USERNAME))")).FindOne()).Properties.memberof | ForEach-Object { ([adsi]"LDAP://$_").cn }

foreach ($group in $adGroups)
	switch ($group)
          "Group Name 1" { Stuff that needs to happen for Group Name 1 }
          "Group Name 2" { Stuff that needs to happen for Group Name 2 }

We eventually just started migrating things to Group Policy Preferences so I never got to see the wide adoption of this script or its effects. At the time, we also still mainly had Server 2003 Domain Controllers.

Thanks for your reply Raymond, but your solution lacks the need for recursion as you wrote :frowning:

I came up with this function to do what I wanted with recursion and all:

Function Test-GroupMembership {
    $Groups = whoami /groups /fo csv | ConvertFrom-Csv | Where-Object {$_.Type -eq "Group"} | ForEach-Object { $_."Group Name"}
    $Groups -contains "$($env:userdomain)\$Group"


Also using GPP a lot, but for more advanced stuff it cannot do enough.