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 {

    [OutputType('ActiveDirectory.Group.Info')]
    [cmdletbinding()]
    Param (
        [parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,Mandatory=$True)]
        [Alias('DistinguishedName')]
        [string]$Group,
        [parameter()]
        [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"
                Break                
            }

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

                $object.pstypenames.insert(0,'ActiveDirectory.Group.Info')
                $object
            }
        }
    }
}

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?
LVL 1
ntr2defAsked:
Who is Participating?
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.

footechCommented:
If those last commands are your actual code, you're missing a ".".  As in it should be
$_.lastmodified
not
$_lastmodified
0
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

0
footechCommented:
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).
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

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
   upMember

Open in new window

0
footechCommented:
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.
0
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
0
footechCommented:
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.
0

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
1
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
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.