2012-07-19 46 views
3

我需要什麼,我希望是一個非常簡單的方法在PowerShell中做到這一點(我運行PowerShell腳本遠程使用絕對管理):PowerShell的:檢查計算機登出

if (computer is logged out) 
{ 
    <run script> 
} 
else 
{ 
    exit 
} 

大部分是我在搜索過程中發現的問題圍繞着與用戶登錄/註銷相關的更復雜的事情展開。我基本上只需要知道電腦當前是否處於登錄提示符狀態。

感謝您的任何和所有幫助 - 你們真棒。

回答

0

根據您的環境中,這可能是一個雷區這裏討論:

Scripting Guy Article

綜上所述,使用來自SysInternals Suite可用PSLoggedOn工具,同時小心翼翼地篩選出可以返回的任何服務帳戶。爲了防止腐爛鏈接這裏是從腳本專家文章上面的使用例子:

$Computers = @( 
, "PC001" 
, "PC002" 
, "PC003" 
, "PC004" 
) 

Foreach ($Computer in $Computers) 
{ 
    [object[]]$sessions = Invoke-Expression ".\PsLoggedon.exe -x -l \\$Computer" | 
     Where-Object {$_ -match '^\s{2,}((?<domain>\w+)\\(?<user>\S+))|(?<user>\S+)'} | 
     Select-Object @{ 
      Name='Computer' 
      Expression={$Computer} 
     }, 
     @{ 
      Name='Domain' 
      Expression={$matches.Domain} 
     }, 
     @{ 
      Name='User' 
      Expression={$Matches.User} 
     } 
    IF ($Sessions.count -ge 1) 
    { 
     Write-Host ("{0} Users Logged into {1}" –f $Sessions.count,  
      $Computer) -ForegroundColor 'Red' 
    } 
    Else 
    { 
     Write-Host ("{0} can be rebooted!" -f $Computer) ` 
      -ForegroundColor 'Green' 
    } 
} 
0

如上所述here,您可以使用下面的代碼片段讓所有登錄的用戶。請注意,這將包含用戶,如系統,本地服務和網絡服務。

Get-WmiObject Win32_LoggedOnUser -ComputerName "myMachine" | 
    Select Antecedent -Unique | 
    % { 
     "{0}\{1}" -f $_.Antecedent.Split('"')[1], $_.Antecedent.Split('"')[3] 
    } 

如果你想看看,才爲人們在某些領域,你可以稍微修改它是這樣的:

Get-WmiObject Win32_LoggedOnUser -ComputerName "myMachine" | 
    Select Antecedent -Unique | 
    % { 
     $domain = $_.Antecedent.Split('"')[1] 
     if($domain -eq "myDomain") { 
      "{0}\{1}" -f $domain, $_.Antecedent.Split('"')[3] 
     } 
    } 
0

使用WMI如果可能的話:

$info = gwmi -class win32_computerSystem -computer sist002ws -ea silentlycontinue | Select-Object username 

if ($info.username.Length -gt 0) 

{$Message = $info.username} 
else 
{ $Message = "No user is logged in locally"} 

$message 
0

這將讓你所有Interactive/RemoteInteractive(終端服務會話)登錄用戶。您可能想要將更多LogonType添加到過濾器。沒有結果意味着在沒有用戶登錄。

http://msdn.microsoft.com/en-us/library/windows/desktop/aa394189(v=vs.85).aspx

Get-WmiObject Win32_LogonSession -ComputerName Server1 -Filter 'LogonType=2 OR LogonType=10' | 
Foreach-Object { $_.GetRelated('Win32_UserAccount') } | 
Select-Object Caption -Unique 
相關問題