0

我有这个 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是否正在执行某些操作:

在此处输入图像描述

4

2 回答 2

1

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

要在 cmd 中查找任何子进程,您可以使用以下内容:

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

更新。正如@LievenKeersmaekers 注意到的那样,如果同时运行多个 cmd,这将无法工作。固定版本:

(Get-Process -name cmd).id | foreach { Get-WmiObject win32_process -filter "ParentProcessId='$_'"}
于 2018-12-27T11:21:02.020 回答
1

以下有点简化,并返回除 之外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
于 2018-12-27T12:09:08.807 回答