I have this PowerShell script that logs off users with IDLE time greater that 1 hour:
#Force script to run.
Set-ExecutionPolicy Unrestricted -force
#Check connected users and save output.
quser|out-file C:\Users\Administrator\Documents\disconectAgora\quser.txt
#Read output with logged in users.
$file = Get-Content C:\Users\Administrator\Documents\disconectAgora\quser.txt
#Obtain IDLE time by using patters.
$pattern = "Disc(.*?)11"
#Obtaons session ID by using patther.
$pattern2 = "adminagora(.*?)Disc"
#Execute query using above patterns.
$result = [regex]::Match($file,$pattern).Groups[1].Value
$result2 = [regex]::Match($file,$pattern2).Groups[1].Value
#Trim file and save both session id and username.
$result = $result -replace(' ','')
$result |out-file C:\Users\Administrator\Documents\disconectAgora\getDCUser.txt
$result2 = $result2 -replace(' ','')
$result2 |out-file C:\Users\Administrator\Documents\disconectAgora\getDCUserID.txt
#If IDLE time is greater than 1 hour user is disconnected.
if ($result -gt '1:00'){
logoff $result2
}
else{
write-host "No users with IDLE time greater than 1 hour found.No users to be logged off."
}
What I want to do is check if a cmd process is running or not, so the user can remain logged on untill this process has ended.
I tought that maybe by running this command get-process | where-object {$_.mainwindowhandle -ne 0} | select-object name, mainwindowtitle
and using regex to get only cmd processes it might do the trick, but it is a very primitive approach.
If you guys have any clue as to how to go about doing this, please let me know.
As requested, here's the output of quser:
Long story short
I need a way to know if something is being executed by CMD other than checking the CPU usage:
To get cmd processes just run get-process -name cmd
To find any child processes within cmd you could use something like this:
Get-WmiObject win32_process | where {$_.ParentProcessId -eq ((Get-Process -name cmd).id)}
Upd. As @LievenKeersmaekers has noticed this could not work in case of several cmds running simultaneously. Fixed version:
(Get-Process -name cmd).id | foreach { Get-WmiObject win32_process -filter "ParentProcessId='$_'"}