SeVroo
SeVroo

Reputation: 1

Powershell script to log out users without specific process

I'm trying to write a script that will log out users which don't have specific process running in their session.

I guess the workflow should look like: Get usernames of all the users logged in, get list of all the processes runnning on the workstation, check if X process is running for Y user, if not, then log user Y out.

So far i managed to create object with all the users currently logged in:

((quser) -replace '^>', '') -replace '\s{2,}', ',' | ConvertFrom-Csv

And list of all the processes running with usernames:

get-process -IncludeUserName

I believe foreach with if inside should do the job, but I can't quite get my head around it. I would appreciate any help.

Thanks!

edit:

$process = get-process -IncludeUserName|Where-Object{
($_.ProcessName -Like "processIneed1*") -or
($_.ProcessName -Like "processIneed2*") -or
($_.ProcessName -Like "processIneed") -or
($_.ProcessName -like 'processIneed3*') -and
($_.username -notlike '*userIwantToSkip1*') -and
($_.username -notlike '*userIwantToSkip2*')
}
$users = Get-RDUserSession | Where-Object -Property UserName -NE 'administrator'
$ActiveUsers = $users.username

foreach ($ProcUser in $process.username){

    foreach ($ActiveUser in $ActiveUsers){

        if ($ProcUser -like "*$ActiveUser*"){
        $ActiveUsers = $ActiveUsers -notlike "*$ActiveUser*"
        }
    }
}

in $activeusers we are left with inactive users. I will most likely change username to session ID and check it this way. Next step will be logging off disconnected users.

Upvotes: 0

Views: 897

Answers (1)

SeVroo
SeVroo

Reputation: 1

$process = get-process -IncludeUserName|Where-Object{
($_.ProcessName -Like "processIneed1*") -or
($_.ProcessName -Like "processIneed2*") -or
($_.ProcessName -Like "processIneed") -or
($_.ProcessName -like 'processIneed3*') -and
($_.username -notlike '*userIwantToSkip1*') -and
($_.username -notlike '*userIwantToSkip2*')
}
$users = Get-RDUserSession | Where-Object -Property UserName -NE 'administrator'
$ActiveUsers = $users.username

foreach ($ProcUser in $process.username){

    foreach ($ActiveUser in $ActiveUsers){

        if ($ProcUser -like "*$ActiveUser*"){
        $ActiveUsers = $ActiveUsers -notlike "*$ActiveUser*"
        }
    }
}

foreach ($inactiveusers in $ActiveUsers){
logoff $inactiveuser
}

Upvotes: 0

Related Questions