Check user group membership in logonscript

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Brian Sprogø Brian Sprogø 1 year, 10 months ago.

  • Author
    Posts
  • #22030
    Profile photo of Brian Sprogø
    Brian Sprogø
    Participant

    Hi everybody,

    FIrst post in here 🙂

    This might seem trivial but I have run out of patience 🙂

    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.

  • #22031
    Profile photo of Brian Sprogø
    Brian Sprogø
    Participant

    Maybe I should say what my problem is 🙂

    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

  • #22032
    Profile photo of Raymond Slieff
    Raymond Slieff
    Participant

    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 }
              etc
            }
    }

    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.

  • #22116
    Profile photo of Brian Sprogø
    Brian Sprogø
    Participant

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

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

    Function Test-GroupMembership {
        param(
            [String]$Group
        )
        
        $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.

You must be logged in to reply to this topic.