Powershell code to add a user temporarily to an AD group

Hi all

I'm working on a workflow to add a user to an AD Group with an End date. In my case 24 hours later.

I have found the powershell code how to do it but it is not functioning as I expected.

If I add the user to the group and then add a removal date it doesn't work.
Has anyone any experience with this? What am I doing wrong?

# BEGIN SCRIPT #

# Hours to stay in the group
$MembershipPeriod = "24"

function temporalGroupMembership($Request){
$GroupDN         = $workflow.SavedObjectProperties("Save Group DN").Get("distinguishedName")
$GroupMember = $workflow.SavedObjectProperties("Save User DN").Get("distinguishedName")
Debug "Group DN : $GroupDN"
Debug "Group Member : $GroupMember"

# End date and time
$TimeGroupOut = Get-Date (Get-Date).Addhours($MembershipPeriod).ToUniversalTime()
$ControlOut = @{}
$ControlOut.add("ScheduledOperation-SetTime",$TimeGroupOut)

#Add-QADGroupMember      -Identity $GroupDN -Member $Groupmember -Control $ControlIn
Add-QADGroupMember        -Identity $GroupDN -Member $Groupmember
Remove-QADGroupMember -Identity $GroupDN -Member $Groupmember -Control $Controlout -Proxy

}

function Debug($Message)
{
$EventLog.ReportEvent($Constants.EDS_EVENTLOG_WARNING_TYPE,[string] $Message)
}
# END SCRIPT #

  • Hi,

    Just adding the script isn't sufficient - did you also include the script in a Workflow? The idea is that you don't have to manually specify the "Remove by" date - you just add someone to an AD group as you'd normally do, and the Workflow ensures that ARS automatically adds an an End date.

    Also see this thread for more info!

  • Thank you for your shift answer. Yes I have a workflow in place and it is working as intended on AD groups in a dedicated OU.
    But the powershell part that actually does the work is not working as it should.

    I also tried working with a Start time and then it did show up in ARS but dit not actualy add the user to the group. 

    # Start time
    $TimeGroupIn = Get-Date (Get-Date).AddMinutes(1).ToUniversalTime()
    $ControlIn = @{}
    $ControlIn.add("ScheduledOperation-SetTime",$TimeGroupIn)

    Does anyone know if you can also give in something like "Now" as $TimeGroupin like it says on the MMC as you do it manualy?

  • OKe figured it out. The time format was the trick.

    This worked for me:

    $TimeGroupOut = Get-Date (Get-Date).AddHours($Membershipperiod).ToUniversalTime() -format "yyyyMMddHHmmss.0Z"
    $ControlOut = @{}
    $ControlOut.add("ScheduledOperation-SetTime",$TimeGroupOut)

    Add-QADGroupMember -Identity $GroupAdministratorsDN -Member $BA_DN -proxy
    Remove-QADGroupMember -Identity $GroupAdministratorsDN -Member $BA_DN -Control $ControlOut -proxy

    This adds the user now and in my example removes the user from the group 24 hours later.