windowspowershellscheduled-tasks

Unable to capture query user output via PowerShell script via Task scheduler as SYSTEM context


I am trying to execute the below PowerShell script as a scheduler job as SYSTEM context on Windows machine.

$AllSessions = C:\WINDOWS\system32\query.exe user 2>&1
$UserSessions = $AllSessions | Select-String -Pattern '^>(?!Testuser1)(\w+)'
$UserSessions | Out-File "D:\output.txt"

While I execute this script locally, I get the result as below in the output file,

>Domain_user              console             1  Active      none   10/3/2024 11:47 AM

While I execute this as part of scheduler task job, the output file does not capture anything.

Can someone please suggest why I am unable to capture the output and how can I achieve this?


Solution

  • tl;dr

    Instead, look for substring Active:

    C:\WINDOWS\system32\query.exe user |
      Select-String ' Active ' |
      Out-File "D:\output.txt"
    

    Important:

    Note:


    Background information:

    The > at the start of one of the lines output by query.exe user (or, equivalently, quser.exe) indicates the caller's session.

    When query user is run: