命令/脚本的Powershell命令用于检查当前登录的活动用户数(本地和域)

时间:2016-06-23 08:34:37

标签: powershell powershell-v2.0 get-wmiobject

我正在寻找命令/脚本来检查当前有多少用户(本地和域)已登录并且在过去30分钟内一直处于活动状态,以便我可以决定是否重启机器。 希望没有Get-ADUser。

我遇到了两个脚本,但在执行时,他们只返回我的信息,在服务器上我可以看到超过5个用户登录。

SCRIPT1

function Get-LoggedOnUser {
#Requires -Version 2.0            
[CmdletBinding()]            
 Param             
   (                       
    [Parameter(Mandatory=$true,
               Position=0,                          
               ValueFromPipeline=$true,            
               ValueFromPipelineByPropertyName=$true)]            
    [String[]]$ComputerName
   )#End Param

Begin            
{            
 Write-Host "`n Checking Users . . . "
 $i = 0            
}#Begin          
Process            
{
    $ComputerName | Foreach-object {
    $Computer = $_
    try
        {
            $processinfo = @(Get-WmiObject -class win32_process -ComputerName $Computer -EA "Stop")
                if ($processinfo)
                {    
                    $processinfo | Foreach-Object {$_.GetOwner().User} | 
                    Where-Object {$_ -ne "NETWORK SERVICE" -and $_ -ne "LOCAL SERVICE" -and $_ -ne "SYSTEM"} |
                    Sort-Object -Unique |
                    ForEach-Object { New-Object psobject -Property @{Computer=$Computer;LoggedOn=$_} } | 
                    Select-Object Computer,LoggedOn
                }#If
        }
    catch
        {
            "Cannot find any processes running on $computer" | Out-Host
        }
     }#Forech-object(ComputerName)       

}#Process
End
{

}#End

}#Get-LoggedOnUser

SCRIPT2

$regexa = '.+Domain="(.+)",Name="(.+)"$';
$regexd = '.+LogonId="(\d+)"$';
$logontype = @{"0"="Local System";
"2"="Interactive";
"3"="Network";
"4"="Batch";
"5"="Service";
"7"="Unlock";
"8"="NetworkCleartext";
"9"="NewCredentials";
"10"="RemoteInteractive";
"11"="CachedInteractive";
};
$logon_sessions = @(gwmi win32_logonsession);
$logon_users = @(gwmi win32_loggedonuser);
$session_user = @{};
$logon_users |% {$_.antecedent -match $regexa > $nul;
$username = $matches[1] + "\" + $matches[2];
$_.dependent -match $regexd > $nul;
$session = $matches[1];
$session_user[$session] += $username};
$logon_sessions |%{$starttime = [management.managementdatetimeconverter]::todatetime($_.starttime);
$loggedonuser = New-Object -TypeName psobject;
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Session" -Value $_.logonid;
$loggedonuser | Add-Member -MemberType NoteProperty -Name "User" -Value $session_user[$_.logonid];
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Type" -Value $logontype[$_.logontype.tostring()];
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Auth" -Value $_.authenticationpackage;
$loggedonuser | Add-Member -MemberType NoteProperty -Name "StartTime" -Value $starttime;
$loggedonuser}

非常感谢帮助。

谢谢, Sambhav

1 个答案:

答案 0 :(得分:0)

如果没有以管理员的身份运行PowerShell ,我相信您无法获取有关其他用户会话的信息。