2012-06-29 31 views
2

all!用WMI查询登录用户的奇怪结果

我试图执行一个非常常见的WMI查询来获取登录到任何给定机器的用户列表。它如下所示(使用PowerShell代码):

$wmi_result = Get-WmiObject -Query "SELECT LogonId FROM Win32_LogonSession WHERE LogonType=2" 
foreach ($obj in $wmi_result) { 
     $id = $obj.LogonId 
     $user_list = Get-WmiObject -Query "ASSOCIATORS OF {Win32_LogonSession.LogonId=$id} WHERE AssocClass=Win32_LoggedOnUser Role=Dependent" | Select Name 
} 

这工作得很好我的本地机器上,但给了我在远程机器上什么都没有。但是,我能够得到这个信息很容易,如果我手工解析相关类的相依性,如下图所示:

$wmi_result = Get-WmiObject -Query "SELECT LogonId FROM Win32_LogonSession WHERE LogonType=2" -ComputerName <computer> 
foreach ($obj in $wmi_result) { 
     $id = $obj.LogonId 
     $user_list = Get-WmiObject -Query "SELECT * FROM Win32_LoggedOnUser" | where {$_.Dependent -match $id} -ComputerName <computer> 
     foreach ($path in $user_list) { 
      $user = ([wmi]$path).name 
     } 
} 

我试图改变WMI连接的模拟和认证水平,无济于事。在WbemTest中运行此查询不会显示任何结果或错误。最后,无论我是直接使用PowerShell还是System.Management,我都可以得到相同的结果。当然,谷歌在这里失败了。

任何人都可以给我一些指示我应该尝试下一步?

谢谢!

回答

1

我已经做了很多这样的事情,我所做的就是让一个函数在远程盒子上运行代码,试试看。只需更改计算机名称,用户名和密码即可。

function remote-pscode ($ServerName,$UserName,$password,$PSCode) 
{ 

# Set the user name you would like to use for the connection 
$global:RemoteUserName = $UserName 
$global:RemoteServerName = $ServerName 
$global:RemoteCode = $PSCode 

# Set the password you would like to use for the connection 
# Check to see if you have a file on you drive c:\cred.txt with a password to use in it,if you don't it will create one 
# for you and ask you for the password you would like to use 

$global:RemotePassword = convertto-securestring $password -AsPlainText -Force 
$global:credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $RemoteUserName,$RemotePassword 

#Create a connection to the remote computer , put a list of IPAddresses or Computer Names. 
$global:session = new-PSSession -ComputerName $RemoteServerName -Credential $credentials 

$ScriptBlock = $executioncontext.invokecommand.NewScriptBlock($RemoteCode) 

invoke-command -Session $session -ScriptBlock $ScriptBlock 

#Close the sessions that where created  
$global:closesession = Get-PSSession 
Remove-PSSession -Session $closesession 


$t = ($wmi_result = Get-WmiObject -Query "SELECT LogonId FROM Win32_LogonSession WHERE LogonType=2" 
foreach ($obj in $wmi_result) 
{$id = $obj.LogonId 
    $user_list = Get-WmiObject -Query "ASSOCIATORS OF {Win32_LogonSession.LogonId=$id} WHERE AssocClass=Win32_LoggedOnUser Role=Dependent" | Select Name 
}) 


remote-pscode -ServerName "testserver" -UserName "testserver\testuser" -password "testpassword" -PSCode "$t"