Search code examples
windowsautohotkeysysinternals

Is it possible to use AutoHotKey to run PSLoggedOn and edit the output in the stream and return the result?


I am using AutoHotKey to build a simple GUI tool that uses the Sysinternals tool PSLoggedOn. First if I use run psloggedon.exe -l -x \\computername I don't get any output at all.

So I tried run %ComSpec% /C psloggedon.exe -l -x 1> %Temp%\psloggedon.txt and that gives me the output in domain\username format for each user logged in.

Like my first example I would rather just run psloggedon and get the output instead of first opening a command prompt; is that possible somehow?

Either way I want to take the output and avoid writing it to a file, but instead edit the output from the output stream to remove the "domain\" part and then just return the username. How can this be done without any third-party software?


Solution

  • This answer to another question on Serverfault shows a way to do it by reading the StdoutRead. I too was looking at a way to avoid using a file but have decided it's actually the simplest option.

    Code copied from user60738

    #include <Constants.au3>
    Dim $line, $line2, $file, $icount, $reg, $reg2, $reg3
    $file = FileOpen("pclist.txt", 0)
    While 1
        $line = FileReadLine($file)
        If @error Then ExitLoop
        $reg3 = ""
        $reg2 = ""
        $reg = ""
        If Ping($line, 200) Then
            $reg = @ComSpec & ' /C "' & @ScriptDir & "\pstools\psloggedon.exe -l -x \\" & $line & '"'
            $reg = Run($reg, "", @SW_HIDE, $STDOUT_CHILD + $STDERR_CHILD)
            While 1
                $reg2 = StdoutRead($reg)
                If @error Then ExitLoop
                If $reg2 Then
                    $reg3 &= $reg2
                EndIf
            WEnd
            If StringInStr($reg3, "Error") Then
                $reg = "Error"
            ElseIf StringInStr($reg3,"No one is logged") Then
                    $reg = "No one is logged on locally."
            Else
                    $reg = StringTrimLeft($reg3, StringInStr($reg3, Chr(13), "", 3))
                    $reg = StringTrimLeft($reg, StringInStr($reg, "\"))
                    $reg = StringTrimRight($reg, StringLen($reg) - StringInStr($reg, Chr(13)))
                    $reg = StringStripWS($reg, 8)
            EndIf
            $icount += 1
            $line2 &= $icount & @TAB & $line & @TAB & $reg & @CRLF
        EndIf
        TrayTip("Psloggedon", $icount & " " & $line & " User: " & $reg, 10)
    WEnd
    FileClose($file)
    ConsoleWrite($line2)
    FileDelete("C:\output.txt")
    FileWrite("C:\output.txt", $line2)
    ShellExecute("C:\output.txt")