Using Sysinternals Console Tools via PowerShell (Part 4)

by Sep 9, 2022

In our previous tips we showed how you can use PowerShell to download, unblock, unzip and then run the Sysinternals console tools from PowerShell. This way you can use tools like psloggedon64.exe to figure out the users that are currently logged on. However, these tools output text to the console.

In our last tip we look at how you can retrieve the command output and use it in your PowerShell code.

Here is what we have done previously:

# download and set up Sysinternals tools
$destinationZipPath = "$env:temp\"
$destinationFolder  = "$env:temp\pstools"
$link = ""
Invoke-RestMethod -Uri $link -OutFile $destinationZipPath -UseBasicParsing
Unblock-File -Path $destinationZipPath
Expand-Archive -Path $destinationZipPath -DestinationPath $destinationFolder -Force
Remove-Item -Path $destinationZipPath
explorer /select,$destinationFolder
# dismiss Sysinternals EULA
$path = "Registry::HKEY_CURRENT_USER\Software\Sysinternals"
$name = 'EulaAccepted'
Set-ItemProperty -Path $path -Name $name -Value 1
# run Sysinternals tool
$destinationFolder  = "$env:temp\pstools"
& "$destinationFolder\PsLoggedOn64.exe"

Now, to really work with the results of a tool like psloggedon64.exe in PowerShell, first add the parameter /? to the command you want to run to see available command line parameters:

$destinationFolder  = "$env:temp\pstools"
& "$destinationFolder\PsLoggedOn64.exe" /?

The result looks like this:

Usage: C:\Users\tobia\AppData\Local\Temp\pstools\PsLoggedOn64.exe [-l] [-x] [\\computername]
    or C:\Users\tobia\AppData\Local\Temp\pstools\PsLoggedOn64.exe [username]
-l     Show only local logons
-x     Don't show logon times
-nobanner Do not display the startup banner and copyright message. 

If you just need a list of locally logged on user names that are logged on to a given machine, next try this:

$destinationFolder  = "$env:temp\pstools"
& "$destinationFolder\PsLoggedOn64.exe" -l -x -nobanner 

To skip the first output line names “Users logged on locally:”, add this:

$destinationFolder  = "$env:temp\pstools"
& "$destinationFolder\PsLoggedOn64.exe" -l -x -nobanner | Select-Object -Skip 1

Now you can store the result in a variable and trim off excess whitespace:

# run Sysinternals tool
$destinationFolder  = "$env:temp\pstools"
$users = & "$destinationFolder\PsLoggedOn64.exe" -l -x -nobanner | Select-Object -Skip 1
# output all logged on users and trim off any leading or trailing whitespace:

The result is a string array with the user names.

If you want to test-drive additional user logins, simply open Notepad as a different user on your machine, i.e. like this (replace USERNAME with the name of the user you want to log in with):

PS> Start-Process -Name notepad -Credential USERNAME -WorkingDirectory c:\ 

Next, run the script again, and it also shows the new user.

Twitter This Tip! ReTweet this Tip!