0

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
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bergie
  • 11
  • 1
  • 3

2 Answers2

0
$machine = "mycomputer"

$user = @(Get-WmiObject -ComputerName $machine -Namespace root\cimv2 -Class Win32_ComputerSystem)

if ($user.Length -gt 0) {
    "Current user is $($user[0].UserName)"
    } else {
    .\mstsc.exe -v $machine
    }
Tim Ferrill
  • 1,648
  • 1
  • 12
  • 15
  • 2
    Please add some narrative around your answer to help the OP – geedubb May 21 '14 at 18:12
  • Thanks for your reply, below is what i have come up with so far. but there are 15 or so users logged in using RDP, i just need to see if there is an RDP session for one specific local user account on the server. does that make sense. – Bergie May 21 '14 at 18:19
0

So I worked with what you had and removed a few things that weren't really needed. I expand the UserName listing and assign it to $Users so I just have an array of user names. Then I check if the desired account is a match for any of them, and if so we pop up the message box, if not we start up MSTSC.

$machine = "ServerNameHere"

# the below command will connect to the server and see all users currently logged in
$Users = Get-WmiObject -ComputerName $machine -Namespace root\cimv2 -Class Win32_ComputerSystem | Select -Expand Username

#This will check if bouair is one of those logged in users.
If($Users -Match "bouair"){
    [system.windows.forms.messagebox]::Show("another user is already logged in!")
}
else { #If it is not, start MSTSC to establish a remote session.
    .\mstsc.exe -v $machine
}

Bonus Function: A simple function I like to have on hand in case I need to pop up a message box:

Function Show-MsgBox ($Text=$(Throw "You must supply the text for the message box."),$Title,[Windows.Forms.MessageBoxButtons]$Button = "OK",[Windows.Forms.MessageBoxIcon]$Icon = "Information"){
[Windows.Forms.MessageBox]::Show("$Text", "$Title", [Windows.Forms.MessageBoxButtons]::$Button, [Windows.Forms.MessageBoxIcon]::Information) | ?{(!($_ -eq "OK"))}
}

Then you can just do Show-MsgBox "Another user is logged on!" and it will pop up with that. You can also specify a window title if desired, and specify what buttons or Icon if desired (typing -Button or -Icon will IntelliSense your options, and tab completion is available for that parameter).

TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56
  • Thanks, after following through this i think it is exactly what i am needing, however when i execute this it keeps throwing error on line 4, there is only one ) right before .UserName – Bergie May 21 '14 at 19:39
  • At line:4 char:96 + ... _ComputerSystem).UserName | Select -Expand Username + ~ Unexpected token ')' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken – Bergie May 21 '14 at 19:41
  • Sorry, my bad, fixed it. I had a ).UserName that needed to be removed that was left over from your code. – TheMadTechnician May 21 '14 at 19:42