trying to create a script to remove a user from a group after an allotted amount of time.

So I'm trying to create a script where a certain amount of time it removes the user from the group as it is only temporary.

This is what i have however to test i want to say if been in for 5 min then remove user then i can bump that up to 24 hours or 48 or even 7 days.

my current script borrows a function, a piece that dumps the group membership info and illustrates that the account is present as well as when it was added:

Function Get-ADGroupMemberDate {

    Param (
        [string]$DomainController = ($env:LOGONSERVER -replace "\\\\")
    Begin {
        #RegEx pattern for output
        [regex]$pattern = '^(?<State>\w+)\s+member(?:\s(?<DateTime>\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})\s+(?:.*\\)?(?<DC>\w+|(?:(?:\w{8}-(?:\w{4}-){3}\w{12})))\s+(?:\d+)\s+(?:\d+)\s+(?<Modified>\d+))?'
    Process {
        If ($Group -notmatch "^CN=.*") {
            Write-Verbose "Attempting to get distinguished name of $Group"

            Try {
                $distinguishedName = ([adsisearcher]"name=$group").Findone().Properties['distinguishedname'][0]
                If (-Not $distinguishedName) {Throw "Fail!"}
            } Catch {
                Write-Warning "Unable to locate $group"

        } Else {$distinguishedName = $Group}

        Write-Verbose "Distinguished Name is $distinguishedName"
        $data = (repadmin /showobjmeta $DomainController $distinguishedName | Select-String "^\w+\s+member" -Context 2)

        ForEach ($rep in $data) {
           If ($rep.line -match $pattern) {
               $object = New-Object PSObject -Property @{
                    Username = [regex]::Matches($rep.context.postcontext,"CN=(?<Username>.*?),.*") | ForEach {$_.Groups['Username'].Value}
                    LastModified = If ($matches.DateTime) {[datetime]$matches.DateTime} Else {$Null}
                    DomainController = $matches.dc
                    Group = $distinguishedName
                    State = $matches.state
                    ModifiedCount = $matches.modified


Open in new window

then using that function i can grab the group I want and its member that was added

get-adgroup test-temp-group | get-adgroupmemberdate 

Open in new window

the return is:
ModifiedCount    : 3
DomainController : SIDC
LastModified     : 11/9/2015 1:21:31 PM
Username         : testuser1
State            : PRESENT
Group            : CN=test-temp-group,OU=Groups,DC=SID,DC=com

Open in new window

so then what i try running to show me the user is:
$date = get-date
$time = $date.addminutes(-5)
get-adgroup test-temp-group | get-adgroupmemberdate | where {$_lastmodified -ge  $time} | ft username,lastmodified

Open in new window

But when i run it returns nothing. Eventually i want to run it so that it looks like:

get-adgroup test-temp-group | get-adgroupmemberdate | where {$_lastmodified -ge  $time} | foreach {remove-adgroupmember test-temp-group $_Username} 

Open in new window

Any ideas?
Who is Participating?

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

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.

If those last commands are your actual code, you're missing a ".".  As in it should be
ntr2defAuthor Commented:
That was a type on my part, it actually is $_.lastmodified however it doesnt display antyhing

this is what the powershell window text looks like:

PS C:\Users\TestAdmin\Documents\Automation> get-adgroup test-temp-group | get-adgroupmemberdate | where {$_.lastmodified -ge  $time} | select username,lastmodified
PS C:\Users\randaverde\Documents\Automation>

Open in new window

In that case I would think it's just your condition that is not being met.  Test with different times (for $time) and operators (i.e. -lt).
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

ntr2defAuthor Commented:
The time was ok i had to change the operator to a less than time. which gave me what i needed however trying to ecompass it to a behavior i didnt have a success:

get-adgroup test-temp-group | get-adgroupmemberdate | where {$_.lastmodified -le  $time} | select username

Open in new window

what i want to do is something like:
$Members = get-adgroup test-temp-group | get-adgroupmemberdate | where {$_.lastmodified -le  $time} | select username

get-adgroup test-temp-group | remove-adgroupmember -identity 'test-temp-group' -member $Members

Open in new window

I then get an error:

Remove-ADGroupMember : Cannot bind parameter 'Members'. Cannot convert value "@{Member=GGPC}" to type
"Microsoft.ActiveDirectory.Management.ADPrincipal". Error: "Cannot convert the "@{Member=GGPC}" value of type
"Selected.System.Management.Automation.PSCustomObject" to type "Microsoft.ActiveDirectory.Management.ADPrincipal"."
At line:1 char:82
+ ... otenforced-sg' $members
+                    ~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Remove-ADGroupMember], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.RemoveADGro

Open in new window

This might work.
$Members = get-adgroup test-temp-group | get-adgroupmemberdate | where {$_.lastmodified -le  $time} | select -expand username

get-adgroup test-temp-group | remove-adgroupmember -member $Members

Open in new window

However, the -members parameter needs a DN, GUID, samaccountname, or SID.  So you probably need to change your regex for the username so it captures the entire DN.
ntr2defAuthor Commented:
it would work however, after looking at the script, using repadmin /showobjmeta captures the display name of the object, not the samaccount name. so what I need to do is something like:
$Members = get-adgroup SC-TempNotEnforced-SG | get-adgroupmemberdate | where {$_.lastmodified -le  $time} | select -expand Member

Open in new window

to capture the user display name accounts
then something like:
$SamAccount = $members | foreach {get-aduser -filter 'name -like "$members"' | get-aduser -properties samaccountname | select -expand samaccountname}

Open in new window

however it doesnt get me what im wanting which is the samaccount name, then i can do:
get-adgroup test-temp-group | remove-adgroupmember -member $SamAccount

Open in new window

So trying to get a second variable to get the ad user account based on the displayname then pull the samaccountname is what im needing to complete this venture. I've been trying different scenarios and im stuck
From what I see repadmin /showobjmeta shows the DN (distinguishName).
Change line 36 of your function to be
Username = [regex]::Matches($rep.context.postcontext,"(?<Username>CN=.*)$") | ForEach {$_.Groups['Username'].Value}

Open in new window

Then the code in my previous post should work.

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
ntr2defAuthor Commented:
You know what that was a better idea and much simpler. thanks for your input and help on this Footech much appreaciated
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

From novice to tech pro — start learning today.