Using Windows PowerShell to check for users on a remote machine and then restart it

Recently I had the Remote desktop services stop responding while I was working out of the office. Since I didn’t really want to go in to reboot the machine I decided I would do it remotely.

Even though it was the weekend I decided that I better check no one else was on the machine doing anything. The following script can be used to see who is on a machine.

param (
    [string]$computername = "."
)

$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ComputerName $computername -ErrorAction SilentlyContinue)
if ($explorerprocesses.Count -eq 0)
{
    "No explorer process found / Nobody interactively logged on"
} else {
    foreach ($i in $explorerprocesses)
    {
        $Username = $i.GetOwner().User
        $Domain = $i.GetOwner().Domain
        $Domain + "\" + $Username + " logged on since: " + ($i.ConvertToDateTime($i.CreationDate))
    }
}

Used as below:

.\UserLoggedOn.ps1 -computername "ComputerName"

Results similar to:

DOMAIN\ACCOUNT1 logged on since: 04/30/2017 12:39:09
DOMAIN\ACCOUNT2 logged on since: 04/30/2017 12:41:16

 

Once I was happy no one was doing anything important I used:

 Restart-Computer -computername "Computername" -force

-force forces restart when users are logged on.