In my Reader to Reader article "Quickly Detect Who Is Logged On to Your Remote Machines", I present a script, WhoLogon.vbs, to detect who is logging on to a remote machine that has been compromised. As I note in the article, my company performs random scans of remote machines on different subnets to see whether they're creating unnecessary traffic and hence are compromised. Most of the compromised machines are in agencies that use our machines. People at the agencies log on with the Active Directory (AD) logon names my company gives them. WhoLogon.vbs, which Listing 1 shows, uses Windows Management Instrumentation (WMI) to identify the logon names used on the compromised machines so that we can disable those accounts.
With PowerShell, you can also identify the user logged onto a remote machine, as the WhoLogon.ps1 script in Listing 2 shows. Let's say you save this script in the D:\powershell\scripts directory. To launch it, you'd enter the following command in the PowerShell command window:
where <machine name> is the name of the target remote machine. Note that you must have administrator permissions on that machine.
WhoLogon.ps1 uses PowerShell's Get-WmiObject cmdlet to access WMI's Win32_ComputerSystem class on the remote computer specified by the Get-WmiObject cmdlet's ComputerName parameter. The parameter's value is retrieved from the command line ($args\[0\]). This part of the script accomplishes the same task as the VBScript code in callout A in Listing 1.
WhoLogon.ps1 then pipes the Get-WmiObject cmdlet's results to the Format-Table cmdlet, which formats the results. The script then uses the Get-WmiObject cmdlet's Property option to retrieve the value of the Win32_OperatingSystem class's UserName property, which is what the VBScript code at callout B in Listing 1 does.
As you can see, the PowerShell code accomplishes the same objective as the VBScript code but with a lot fewer lines. As its name indicates, this shell is truly powerful.
Share Your Scripting Experiences
Share your scripting discoveries, comments, solutions to problems, and experiences with products. Email your contributions to firstname.lastname@example.org. Please include your full name and phone number. We edit submissions for style, grammar, and length. If we print your submission, you’ll get $100.