1

全部!

我正在尝试执行一个非常常见的 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
 }

这在我的本地机器上运行良好,但在远程机器上什么也没有。但是,如果我手动解析关联类的 Dependent 属性,我可以很容易地获得这些信息,如下所示:

 $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,我都会得到相同的结果。当然,谷歌在这里让我失望了。

谁能给我一些关于下一步我应该尝试什么的指示?

谢谢!

4

1 回答 1

0

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

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"
于 2012-07-04T13:01:19.463 回答