【发布时间】:2022-01-13 08:24:47
【问题描述】:
首先感谢您的时间和帮助。
我的问题是我在获取远程登录用户的名称时行为不稳定。我想向特定的计算机或 IP 列表发送消息,如果有人登录,则获取看到该消息的人。 为此,我创建了一个脚本,该脚本应逐个读取并获取计算机名称,并查看是否已连接。如果是,获取用户名,发送消息,然后在表格中显示并在 txt 文件中写入结果:
#We read the "Lista" file with IPs or computer names, works with both
$PCLIST = Get-Content 'C:\Users\XXXX\Desktop\Lista.txt'
#Add the date tot he txt files to be created
$Fecha = date
echo $Fecha > "C:\Users\XXXX\Desktop\ListOffline.txt"
echo $Fecha > "C:\Users\XXXX\Desktop\Done.txt"
#We check every computer and if ONLINE send the message
foreach ($computer in $PCLIST)
{
if ((Test-NetConnection -ComputerName $computer -WarningAction SilentlyContinue).PingSucceeded -eq $true) #If ping back is succesfull then write the message
{
$Usuario = (Get-WmiObject -Class win32_computersystem -ComputerName $computer).UserName
if ((Get-WmiObject -Class win32_computersystem -ComputerName $computer).UserName) {" "} else {$Usuario = "Usuario Remoto"}
$output = @{ 'Computer_Name / IP' = $computer }
$output.Usuario_Conectado = (Get-WmiObject -Class win32_computersystem -ComputerName $computer).UserName
msg * /server:$computer "Hey!!" $Usuario ", Something meaninfull :) " #Message1
msg * /server:$computer "And something more meaningfull even ;)" #Message2
echo "$computer, avisado y recibido por $Usuario" >> "C:\Users\XXXX\Desktop\Done.txt"
}
else
{
$output = @{'Computer_Name / IP' = $computer }
$output.Usuario_Conectado = "OFFLINE"
echo $Computer >> "C:\Users\XXXX\Desktop\ListOffline.txt"
}
[PSCustomObject]$output
}
消息部分按预期工作,计算机在登录时可以看到消息,但是:
- 我无法获取计算机列表中远程登录用户的名称,我将我的用户名和其他用户名设为空名。在一些奇怪的变化中,我可以,但再也找不到问题所在了。作为先决条件,我允许 Win RM 和防火墙配置:
- 我去了将要发送它的计算机并修改了注册表:“reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v "AllowRemoteRPC" /t "REG_DWORD" /d "1 " /f"
- 并打开 sshnet 以允许远程访问获取名称:“netsh firewall set service remoteadmin enable”
在橙色圆圈中的图像中应该是远程用户登录但我得到空名称
- 我想在用户登录时发送消息,作为远程用户或在控制台上,现在即使用户没有收到任何消息,也会写入“完成”的 txt 文件...
所以,这个调用应该有一个问题:“(Get-WmiObject -Class win32_computersystem -ComputerName $computer).UserName”来获取名称,这有效但我无法获取远程登录用户计算机上的名称不再......有什么想法或建议吗?如果可用且更容易,我可以接受以其他形式获取它们。
谢谢,最好的, 娟
【问题讨论】:
-
您是否手动测试过您的查询?
Get-CimInstance –ComputerName computername –ClassName Win32_ComputerSystem | Select-Object UserName -
您可以使用此处开发的功能测试远程用户登录 - 如何使用 PowerShell 远程查找登录用户 4sysops.com/archives/…>
-
你为什么重复
(Get-WmiObject -Class win32_computersystem -ComputerName $computer).UserName一次就足够了? -
Win32_ComputerSystem.UserName可能只会获取连接控制台的用户。如果您查询Win32_LoggedOnUserassociation class,您会得到任何可行的结果吗? -
谢谢,这个:4sysops.com/archives/… 我以前见过,但你可以看到它使用相同的调用来获取远程用户。我什至复制并使用了他的函数,但远程函数的名称仍然是空的......所以同样的错误
标签: powershell remote-access powershell-4.0