community.spiceworks.com Open in urlscan Pro
45.60.13.212  Public Scan

URL: https://community.spiceworks.com/topic/2081941-check-logged-locked-status-of-1-remote-pc-with-powershell-script
Submission: On June 19 via manual from US — Scanned from DE

Form analysis 1 forms found in the DOM

<form>
  <i class="1687207859622 mag-glass"></i>
  <input class="1687207859622 search-input" autocomplete="off" placeholder="Search Spiceworks">
  <i class="clean-icon"></i>
  <div class="1687207859622 trending-topics"></div>
  <div class="1687207859622 search-box-results"></div>
</form>

Text Content

Home
 * News & Insights
   * News & Insights Home
   * Innovation
   * IT Careers & Skills
   * Cloud
   * Cyber Security
   * Future of Work
   * All Categories
   * Marketing
   * HR
   * Finance
 * Community
   * Ask question
   * Community Home
   * Spiceworks Originals
   * Cloud
   * Collaboration
   * Networking
   * Water Cooler
   * Windows
   * All forums
   * How-Tos
   * Scripts
   * Vendors
   * Meetups
 * Reviews
 * Online Events


Login Join
Login Join


 * Home
 * Programming
 * PowerShell


CHECK LOGGED/LOCKED STATUS OF 1 REMOTE PC WITH POWERSHELL SCRIPT

Posted by itsupportprivate on Nov 4th, 2017 at 1:23 PM
Solved
PowerShell

Hi,

I am trying to come up with an easy but accurate way for me to see if a Domain
computer is logged in/locked/logged out/turned off.

I have the following so far, but not sure how to get it to work with my admin
account, any ideas please;

Powershell

#Get Admin Account details
Get-Credential

#To Query a PC for Current Logged in State
$ComputerName = Read-host "Please enter the Hostname"

query user /server:$ComputerName -credential 


Spice (2) Reply (10)
flagReport
itsupportprivate
anaheim

POPULAR TOPICS IN POWERSHELL

Installing Multiple Programs, getting "Do you want to run this file... Window
upgrade Iterating through AD - Cant complete iteration before writing variable
Unexpected token in expression or statement error Get List of Groups an AD Group
is nested in View all topics

check Best Answer
An Evil Penguin
This person is a verified professional.
Verify your account to enable IT peers to see that you are a professional.
thai pepper
Nov 6th, 2017 at 9:20 AM checkBest Answer

This is the core of what I use to do this:

Powershell

    Foreach ($Computer in $Computername)
        {
        $Online = $False
        $User = $False
        $Locked = $False
        If (Test-Connection $Computer -Count 2 -Quiet) 
            {
            $Online = $True 
            If ($Credential) 
                {
                $User = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer -Credential $Credential | Select-Object -ExpandProperty UserName -ErrorAction Stop
                }
            Else
                {
                $User = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer | Select-Object -ExpandProperty UserName -ErrorAction Stop
                }
            If (Test-RemoteRegistry -Enable -ComputerName $Computer)
                {
                If ((Get-Process logonui -ComputerName $Computer -ErrorAction SilentlyContinue) -and ($user))
                    {
                    $Locked = $True
                    }
            }
            }
        $Output = New-Object PSObject
        $Output | Add-Member noteproperty ComputerName $Computer
        $Output | Add-Member noteproperty Online $Online
        $Output | Add-Member noteproperty Username $User
        $Output | Add-Member noteproperty Locked $Locked
        $Output
        }


Test-RemoteRegistry is a separate function that polls for the status of the
Remote Registry service as that is not always in a consistent state in my
environment. For some reason Remote registry is needed for get-process remotely.

Adapt or remove that as needed. I've also just noticed that I never passed
credentials to the Get-Process section if they were given!


flagReport
2 found this helpful thumb_up thumb_down
View Best Answer in replies below


10 REPLIES

 * Chris Walten
   cayenne
   Nov 5th, 2017 at 12:44 PM
   
   qwinsta is something you need to look at.
   
   flagReport
   Was this post helpful? thumb_up thumb_down
 * OP itsupportprivate
   anaheim
   Nov 5th, 2017 at 9:55 PM
   
   Thanks. Ill look into
   
   flagReport
   Was this post helpful? thumb_up thumb_down
 * An Evil Penguin
   This person is a verified professional.
   Verify your account to enable IT peers to see that you are a professional.
   thai pepper
   Nov 6th, 2017 at 9:20 AM checkBest Answer
   
   This is the core of what I use to do this:
   
   Powershell
   
       Foreach ($Computer in $Computername)
           {
           $Online = $False
           $User = $False
           $Locked = $False
           If (Test-Connection $Computer -Count 2 -Quiet) 
               {
               $Online = $True 
               If ($Credential) 
                   {
                   $User = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer -Credential $Credential | Select-Object -ExpandProperty UserName -ErrorAction Stop
                   }
               Else
                   {
                   $User = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer | Select-Object -ExpandProperty UserName -ErrorAction Stop
                   }
               If (Test-RemoteRegistry -Enable -ComputerName $Computer)
                   {
                   If ((Get-Process logonui -ComputerName $Computer -ErrorAction SilentlyContinue) -and ($user))
                       {
                       $Locked = $True
                       }
               }
               }
           $Output = New-Object PSObject
           $Output | Add-Member noteproperty ComputerName $Computer
           $Output | Add-Member noteproperty Online $Online
           $Output | Add-Member noteproperty Username $User
           $Output | Add-Member noteproperty Locked $Locked
           $Output
           }
   
   
   Test-RemoteRegistry is a separate function that polls for the status of the
   Remote Registry service as that is not always in a consistent state in my
   environment. For some reason Remote registry is needed for get-process
   remotely.
   
   Adapt or remove that as needed. I've also just noticed that I never passed
   credentials to the Get-Process section if they were given!
   
   
   flagReport
   2 found this helpful thumb_up thumb_down
 * OP itsupportprivate
   anaheim
   Nov 6th, 2017 at 10:17 AM
   
   Thanks. Ill give it a try.
   
   flagReport
   Was this post helpful? thumb_up thumb_down
 * philgman
   This person is a verified professional.
   Verify your account to enable IT peers to see that you are a professional.
   cayenne
   Nov 7th, 2017 at 4:16 PM
   
   i use this to remote check the event logs. 
   
   Powershell
   
   Param (
    [string]$Computer = (Read-Host Remote computer name),
    [int]$Days = 20
    )
   $events = @()
   $events += Get-WinEvent -ComputerName $Computer -FilterHashtable @{ 
           LogName='Security'
       Id=@(4800,4801)
       StartTime=(Get-Date).AddDays(-$Days) 
   }
   $events += Get-WinEvent -ComputerName $Computer -FilterHashtable @{ 
           LogName='System'
       Id=@(7000,7001)
       StartTime=(Get-Date).AddDays(-$Days) 
   }
   
   $type_lu = @{
       7001 = 'Logon'
       7002 = 'Logoff'
       4800 = 'Lock'
       4801 = 'UnLock'
   }
   
   $ns = @{'ns'='http://schemas.microsoft.com/win/2004/08/events/event'}
   $target_xpath = "//ns:Data[@Name='TargetUserName']"
   $usersid_xpath = "//ns:Data[@Name='UserSid']"
   
   If($events) {
       $results = ForEach($event in $events) {
           $xml = $event.ToXml()
           Switch -Regex ($event.Id) {
               '4...' {
                   $user = (
                       Select-Xml -Content $xml -Namespace $ns -XPath $target_xpath
                   ).Node.'#text'
                   Break            
               }
               '7...' {
                   $sid = (
                       Select-Xml -Content $xml -Namespace $ns -XPath $usersid_xpath
                   ).Node.'#text'
                   $user = (
                       New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList $sid
                   ).Translate([System.Security.Principal.NTAccount]).Value
                   Break
               }
           }
           New-Object -TypeName PSObject -Property @{
               Time = $event.TimeCreated
               Id = $event.Id
               Type = $type_lu[$event.Id]
               User = $user
           }
       }
       If($results) {
           #$results
           $Results | Sort Time -Descending | Out-GridView
       }
   }
   
   
   i also have a vbs that will scan an ip range (never got aroiund to adapting
   this to powershell).
   
   VB.net
   
   On Error Resume Next
   
   Dim FSO
   Dim objStream
   
   Const TriStateFalse = 0
   Const FILE_NAME = "Logged_In_Users.csv"
   
   Set FSO = CreateObject("Scripting.FileSystemObject")
   
   Set objStream = FSO.CreateTextFile(FILE_NAME, _
   	True, TristateFalse)
   
   
   
   '************	CHANGE THIS **************
   strSubnetPrefix = "192.168.1."
   intBeginSubnet = 100
   intEndSubnet = 120
   
   For i = intBeginSubnet To intEndSubnet
   	strComputer = strSubnetPrefix & i
   		'strcomputer = inputbox("Enter Computer Name or IP")
   		if strcomputer = "" then
   			wscript.quit
   		else
   
   		'ping it!
   		Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
   			("select * from Win32_PingStatus where address = '" & strcomputer & "'")
   		For Each objStatus in objPing
   			If IsNull(objStatus.StatusCode) or objStatus.StatusCode<>0 Then 
   				'request timed out
   				'msgbox(strcomputer & " did not reply" & vbcrlf & vbcrlf & _
   						'"Please check the name and try again")
   			else
   				'who's there?
   				set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & _
   			strComputer & "\root\cimv2")
   				Set colSettings = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
   				For Each objComputer in colSettings 
   										objStream.WriteLine objComputer.name & "," & objcomputer.username & "," & objcomputer.domain _
   					& "," & strcomputer
   					'msgbox("System Name: " & objComputer.Name & vbcrlf & "User Logged in : " & _
   					'objcomputer.username  & vbcrlf & "Domain: " & objComputer.Domain)
   				Next
   			end if
   		next
   		end if
   Next
   
   Msgbox("Done Collecting")
   
   'cleanup
   set objwmiservice = nothing
   set colsettings = nothing
   set objping = nothing
   
   
   flagReport
   1 found this helpful thumb_up thumb_down
 * Craig582
   This person is a verified professional.
   Verify your account to enable IT peers to see that you are a professional.
   cayenne
   May 15th, 2018 at 10:51 AM
   
   > An Evil Penguin wrote:
   > 
   > This is the core of what I use to do this:
   > 
   > Powershell
   > 
   >     Foreach ($Computer in $Computername)
   >         {
   >         $Online = $False
   >         $User = $False
   >         $Locked = $False
   >         If (Test-Connection $Computer -Count 2 -Quiet) 
   >             {
   >             $Online = $True 
   >             If ($Credential) 
   >                 {
   >                 $User = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer -Credential $Credential | Select-Object -ExpandProperty UserName -ErrorAction Stop
   >                 }
   >             Else
   >                 {
   >                 $User = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer | Select-Object -ExpandProperty UserName -ErrorAction Stop
   >                 }
   >             If (Test-RemoteRegistry -Enable -ComputerName $Computer)
   >                 {
   >                 If ((Get-Process logonui -ComputerName $Computer -ErrorAction SilentlyContinue) -and ($user))
   >                     {
   >                     $Locked = $True
   >                     }
   >             }
   >             }
   >         $Output = New-Object PSObject
   >         $Output | Add-Member noteproperty ComputerName $Computer
   >         $Output | Add-Member noteproperty Online $Online
   >         $Output | Add-Member noteproperty Username $User
   >         $Output | Add-Member noteproperty Locked $Locked
   >         $Output
   >         }
   > 
   > 
   > Test-RemoteRegistry is a separate function that polls for the status of the
   > Remote Registry service as that is not always in a consistent state in my
   > environment. For some reason Remote registry is needed for get-process
   > remotely.
   > 
   > Adapt or remove that as needed. I've also just noticed that I never passed
   > credentials to the Get-Process section if they were given!
   
   
   
   I tried this out yesterday and it worked wonderfully, I then adapted it
   slightly removing the pinging as I will be running it from PDQ inventory so
   will already know if it is online or not, plus I was just trying to cut down
   the time it was taking to run. This seemed to work.
   
   Powershell
   
   $computername = '$(Computer:TARGET)'
   $host.ui.RawUI.WindowTitle = "Logon status of $computer"
       Foreach ($Computer in $Computername)
           {
           $User = $False
           $Locked = $False
               {
                   {
                   $User = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer -Credential $Credential | Select-Object -ExpandProperty UserName -ErrorAction Stop
                   }
               Else
                   {
                   $User = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer | Select-Object -ExpandProperty UserName -ErrorAction Stop
                   }
                   {
                   If ((Get-Process logonui -ComputerName $Computer -ErrorAction SilentlyContinue) -and ($user))
                       {
                       $Locked = $True
                       }
               }
               }
           $Output = New-Object PSObject
           $Output | Add-Member noteproperty ComputerName $Computer
           $Output | Add-Member noteproperty Username $User
           $Output | Add-Member noteproperty Locked $Locked
           $Output
           }
   
   
   
   
   Today I’ve just gone to test it and the script doesn’t work properly, I’m
   getting the following not matter whether a user is logged on or not:
   
   Powershell
   
                   {
                   $User = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer -Credential $Credential |
   Select-Object -ExpandProperty UserName -ErrorAction Stop
                   }
               Else
                   {
                   $User = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer | Select-Object
   -ExpandProperty UserName -ErrorAction Stop
                   }
                   {
                   If ((Get-Process logonui -ComputerName $Computer -ErrorAction SilentlyContinue) -and ($user))
                       {
                       $Locked = $True
                       }
               }
   
   
   ComputerName Username Locked
   ------------ -------- ------
   03-05           False  False
   
   
   
   
   I don’t have a great knowledge of PowerShell but I can usually figure out
   where I’ve gone wrong. Any help would be truly appreciated.
   
   
   flagReport
   Was this post helpful? thumb_up thumb_down
 * An Evil Penguin
   This person is a verified professional.
   Verify your account to enable IT peers to see that you are a professional.
   thai pepper
   May 15th, 2018 at 11:48 AM
   
   Difficult to say without something to test with or knowledge of your systems.
   
   I'd say try calling each of the queries on that test machine one by one to
   inspect the Output. Could be something is acting up on that machine or is
   encountering something I've not considered.
   
   Also I think I set it to just return False for everything if it doesn't ping,
   so that might be getting involved?
   
   Edit: Also not used PDQDeploy myself so not sure if that would throw any
   spanners in to the works?
   
   
   Spice (1) flagReport
   1 found this helpful thumb_up thumb_down
 * M Boyle
   This person is a verified professional.
   Verify your account to enable IT peers to see that you are a professional.
   ghost chili
   May 15th, 2018 at 12:09 PM
   
   You should really ask a new question on this one.
   
   
   You are chopping code out (like if statements) but leaving behind the braces
   { } and random else statements.
   
   
   Provide some more of the code for better context. .
   
   
   Spice (2) flagReport
   Was this post helpful? thumb_up thumb_down
 * Craig582
   This person is a verified professional.
   Verify your account to enable IT peers to see that you are a professional.
   cayenne
   May 16th, 2018 at 2:56 PM
   
   I worked out that I missed an IF which sorted out the user part. Working out
   what I’d done wrong to get the locked part right took it’s time. But after
   some serious testing and tweaking, this is what I have ended up with. This
   works. It probably could be better, but the main thing is it works.
   
   Massive thanks to you An Evil Penguin for the original script. 
   Powershell
   
   $computer = '$(Computer:TARGET)'
   $host.ui.RawUI.WindowTitle = "Logon details of $(Computer:TARGET)"
   $ErrorActionPreference = 'SilentlyContinue'
   $users = $false
   $locked = $false
   $users = (Get-WmiObject -Class win32_computersystem -ComputerName $computer).username.Split("\")[1]
    If ((Get-Process logonui -ComputerName $Computer) -and ($users))
                       {
                       $Locked = $True
                       }
   foreach ($user in $users) {
           $Output = New-Object PSObject
           $Output | Add-Member noteproperty Computer $Computer
           $Output | Add-Member noteproperty Username $User
           $Output | Add-Member noteproperty Locked $Locked
           $Output
   }
   
   
    * local_offer Tagged Items
    * An Evil Penguin
   
   Spice (1) flagReport
   Was this post helpful? thumb_up thumb_down
 * An Evil Penguin
   This person is a verified professional.
   Verify your account to enable IT peers to see that you are a professional.
   thai pepper
   May 16th, 2018 at 2:58 PM
   
   Glad it worked out in the end! :)
   
   
   flagReport
   Was this post helpful? thumb_up thumb_down

lock

This topic has been locked by an administrator and is no longer open for
commenting.

To continue this discussion, please ask a new question.




READ THESE NEXT...


 * SNAP! -- DATA CAPS, COSMIC NAVIGATION, APPARENT CURE FOR EPILEPSY, CUTE
   ROBOTS
   
   Spiceworks Originals
   
   Your daily dose of tech news, in brief. Welcome to the Snap! Flashback: June
   19, 1623: Blaise Pascal is Born (Read more HERE.) Bonus Flashback: June 19,
   1963: Vostok 5 & Vostok 6 return to Earth (Read more HERE.) You need to hear
   this....

 * 


 * SPARK! PRO SERIES – 19TH JUNE 2023
   
   Spiceworks Originals
   
   It has been 7 years since we lost Anton Yelchin.  He was as superb Checkov,
   but an even better Odd Thomas (see trailer below), which I highly recommend
   watching.  We can only imagine what other characters he coul...


 * NERD JOURNEY # 220 - JOHN GOT FIRED
   
   Best Practices & General IT
   
   What would go through your mind if you woke up in the middle of the night
   only to find out you had been laid off?  Processing the onset of emotions
   that come next isn't easy.  When this happened to John White earlier in the
   year, he needed to decide what ...


 * HOW MUCH EMAIL IS IN YOUR INBOX RIGHT NOW?
   
   Spiceworks
   
   I was reading today some interesting email statistics (Reference site Opens a
   new window, Reference site Opens a new window, and there were a few others
   that basically agreed with those numbers).--The average office worker gets
   120-126 emails a day.Not su...


 * WHAT ARE THE PROS AND CONS OF A IT CAREER IN ACADEMIA/ SCHOOL CAMPUSES?
   
   IT & Tech Careers
   
   After working in IT for a while I figure I want to take my career path in
   education/academia and move away from corporate office.Example of such jobs:
   University Network Engineer, Community College End User Support, Elementary
   School Computer Lab Technici...

 * About
 * Contact
 * Support
 * Press / Media
 * Careers
 * SpiceWorld
 * Blog
 * * 
   * 
   * 
   * 

 * Sitemap
 * Privacy Policy
 * Terms of Use
 * Guidelines
 * Accessibility Statement
 * Do Not Sell My Personal Information
 * © Copyright 2006 - 2023 Spiceworks Inc.






WE CARE ABOUT YOUR PRIVACY

If you consent, we and our partners can store and access personal information on
your device to provide a more personalised browsing experience. This is
accomplished through processing personal data collected from browsing data
stored in cookies. You can provide/withdraw consent and object to processing
based on a legitimate interest at any time by clicking on the ‘Manage
Preferences’ button.Our Privacy Policy


WE AND OUR PARTNERS PROCESS DATA TO:

Store and/or access information on a device. Personalised ads and content, ad
and content measurement, audience insights and product development. Our Partners

Reject All I Accept
More Options