我正在寻找构建一个 PowerShell 脚本,该脚本将查看本地用户帐户是否已在远程计算机上登录。如果是这样,它将弹出一条消息,说明用户已登录。如果用户未登录,它将打开 mstsc 以便用户可以登录。
我发现下面的代码效果很好,但它似乎只看到域帐户。从那里我不确定如何根据用户是否登录来传递结果并做出响应。
@(Get-WmiObject -ComputerName $machine -Namespace root\cimv2 -Class Win32_ComputerSystem)[0].UserName;
更新了代码。基本上我需要查看 RDP 会话是否正在使用本地用户帐户。那有意义吗?
$machine = "ServerNameHere"
$temp1 = "C:\temp\user.txt"
$Word = "JDoe"
# The below command will connect to the server and see if user bouair is currently logged in
@(Get-WmiObject -ComputerName $machine -Namespace root\cimv2 -Class Win32_ComputerSystem)[0].UserName | Out-File $temp1 -Append
If((Get-Content $temp1).Contains($Word))
{
[system.windows.forms.messagebox]::Show("another user is already logged in!");
}
else {
.\mstsc.exe -v $machine
}
Remove-Item $temp1
exit
Get-WmiObject 命令的问题之一是它没有在我的服务器上拉取 RDP 会话。然后我遇到了一个博客,用户使用 quser 来拉取所有用户,然后我修改了代码以在我的环境中工作。此代码非常适合我们的团队,其他人可能会从中受益。下一步是将空闲时间和状态拉到消息块中,但那是另一天。
param( $ComputerName = 'ServerNameNere' )
process {
$File1 = "C:\temp\user.txt"
$word = "UserNameHere"
Remove-Item $File1
foreach ($Computer in $ComputerName) {
quser /server:$Computer | Select-Object -Skip 1 | ForEach-Object {
$CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
$HashProps = @{
UserName = $CurrentLine[0] | Out-File $file1 -Append
ComputerName = $Computer | Out-File $file1 -Append
}
if ($CurrentLine[2] -eq 'Disc') {
$HashProps.SessionName = $null | Out-File $file1 -Append
$HashProps.Id = $CurrentLine[1] | Out-File $file1 -Append
$HashProps.State = $CurrentLine[2] | Out-File $file1 -Append
$HashProps.IdleTime = $CurrentLine[3] | Out-File $file1 -Append
$HashProps.LogonTime = $CurrentLine[4..6] -join ' ' | Out-File $file1 -Append
}
else {
$HashProps.SessionName = $CurrentLine[1] | Out-File $file1 -Append
$HashProps.Id = $CurrentLine[2] | Out-File $file1 -Append
$HashProps.State = $CurrentLine[3] | Out-File $file1 -Append
$HashProps.IdleTime = $CurrentLine[4] | Out-File $file1 -Append
$HashProps.LogonTime = $CurrentLine[5..7] -join ' ' | Out-File $file1 -Append
}
New-Object -TypeName PSCustomObject -Property $HashProps |
Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime
}
}
If((Get-Content $file1).Contains($Word))
{
[system.windows.forms.messagebox]::Show("another user is already logged in!");
}
else {
mstsc.exe -v $machine
}
}