所有!
我正在尝试执行一个非常常见的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,我都会得到相同的结果。当然,Google在这里让我失望。
有人能给我一些关于我接下来要尝试的内容吗?
谢谢!
答案 0 :(得分: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"