PowerShell - 用户会话管理

PowerShell - User session management

我有这个 PowerShell 脚本可以注销空闲时间超过 1 小时的用户:

#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."
    }

我想做的是检查 cmd 进程是否 运行,以便用户可以保持登录状态直到该进程结束。

我认为也许可以通过 运行 这个命令 get-process | where-object {$_.mainwindowhandle -ne 0} | select-object name, mainwindowtitle 并使用正则表达式只获取 cmd 进程它可能会成功,但这是一种非常原始的方法。

如果你们知道如何进行此操作,请告诉我。

根据要求,这是 quser 的输出:

长话短说

除了检查 CPU 用法之外,我需要一种方法来了解 CMD 是否正在执行某些操作:

只获取 cmd 进程 运行 get-process -name cmd

要在 cmd 中查找任何子进程,您可以使用如下方法:

Get-WmiObject win32_process | where {$_.ParentProcessId -eq ((Get-Process -name cmd).id)}

更新。 正如@LievenKeersmaekers 所注意到的那样,这在多个 cmd 运行ning 同时存在的情况下不起作用。固定版本:

(Get-Process -name cmd).id | foreach { Get-WmiObject win32_process -filter "ParentProcessId='$_'"}

以下内容略有简化,returns 除 adminagora 外,其他用户已断开会话超过一个小时

(& quser) -split "`n" | ? {$_ -match "(?<!adminagora).*?Disc\s+\d:\d{2}"}

细分

(& quser) -split "`n"  -- Executes quser 
                          Splits each line on newline to pass through the pipeline
? {$_ -match           -- Where the current item matches the regex
(?<!adminagora)        -- Use a negative lookbehind to exclude adminagora
.*?Disc                -- match any characters as few times as possible up until Disc. 
\s+\d:\d{2}            -- match any space character followed by
                       -- a digit, a colon and two digits