I am looking to build a PowerShell script that will see if a local user account is logged in on a remote machine. If so, it will pull up a message saying the user is logged in. If the user is not logged in, it would open mstsc so a user can log in.
The below code I found works great, but it appears to only see domain accounts. And from there I am not sure how to pass results on and respond based on if the user is logged in or not.
@(Get-WmiObject -ComputerName $machine -Namespace root\cimv2 -Class Win32_ComputerSystem)[0].UserName;
Updated code. Basically i need to see if a local user account is being used by an RDP session. does that make sense?
$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
One of my problems with the Get-WmiObject command was it wasn't pulling RDP sessions on my server. I then ran across a blog where users were using quser to pull all the users, i then modified the code to work in my environment. this code works perfectly for our group and others may benefit from it. the next step is to pull teh idletime and state into the message block, but that is for another day.
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
}
}