Nick
Getchell

I'm a Senior DevOps Engineer overseeing releases, developer experience, and cloud infrastructure. I have 20+ years of running web apps and systems administration both during my personal time and in my career.

I write about my hobbies, including technology, movies, books, and music.

Engineering › Systems Administration · · 2 min read

Expiring Group Memberships

As a systems administrator working with Active Directory your probably proficient in granting access to network resources. How good are you at removing permissions once the access is no longer needed? Probably not as good. Enter Expiring Group Membership in Active Directory. You can specify how long an object belongs in a group. Active Directory handles the removal for you.

To use Expiring Group Memberships, make sure that the feature is enabled in your forest. This is a feature added in Server 2016 and is not on by default.

## If Enabled EnabledScopes 
## won't be empty

$Forest = Get-ADForest
Get-ADOptionalFeature -Identity 'Privileged Access Management Feature'

## Enable Privileged Access

$enableADOptionalFeatureSplat = @{
    Scope = 'ForestOrConfigurationSet'
    Target = $Forest
    Identity = 'Privileged Access Management Feature'
}
Enable-ADOptionalFeature @enableADOptionalFeatureSplat

Existing groups should work but if you don't have one, create a group now.

$newADGroupSplat = @{
    GroupCategory = 'Security'
    DisplayName = "Temporary Membership"
    GroupScope = 'Global'
    Name = 'TempGroup'
}
New-ADGroup @newADGroupSplat

Now add the membership using the MemberTimeToLive parameter.

$addADGroupMemberSplat = @{
    Members = 'ngetchell'
    MemberTimeToLive = ( New-Timespan -Days 365)
    Identity = 'TempGroup'
}
Add-ADGroupMember @addADGroupMemberSplat

Expiring Membership Report

Now to generate a report to show off a members and their membership timespan. You could even pipe to Excel if you'd prefer.

Get-ADGroup -Identity TempGroup -ShowMemberTimeToLive -Properties members | 
    Select-Object -ExpandProperty members | 
    ForEach-Object {
    if ( $_ -match '<TTL=' ) {
        $ttlstring, $DN = $_ -split '>'

        [int]$ttl = $ttlstring -replace '<TTL='
        $Timespan = New-Timespan -Seconds $ttl
        
        [pscustomobject]@{

            MemberDN   = $DN -replace "^,", ""
            TTL        = $Timespan
            ExpirypublishDate:$((Get-Date).Add($Timespan))

        } 
    }
    else {
        [pscustomobject]@{

            MemberDN   = $_
            TTL        = 0
            ExpirypublishDate:0

        } 
    }
} | Export-Excel -Path ~\Desktop\ExpiringGroupMembers.xlsx

Tagged PowerShell