Use PowerShell to Find the Logon User for Scheduled Tasks and Services on the Network

Today, we have a script that will query all computers on the domain for scheduled tasks and services that run as a specified user then outputs it to a CSV file.  For this to work, the computer running the script needs to have the Active Directory Module for Windows Powershell installed and the account running it needs to be a domain administrator.  Let’s break the script down.

Import-Module ActiveDirectory

First, we need to import the Active Directory Module into the PowerShell session.  Once we do that, we need to know which username we are looking for.  We can do that with the following line of code.

$user = Read-Host “Please enter the fully qualified username of the user that the service/task is running as.  (DOMAIN\username)”

The above will show a prompt in the PowerShell window to input the username we are looking for here.  It is important to include the domain as well.  The next code block is where the magic happens.

Get-ADComputer -Filter * | foreach {
$pc = $_.Name
$rtn = Test-Connection -ComputerName $_.DnsHostName -Count 1 -BufferSize 16 -Quiet
if ($rtn -match “True”) {
$service += Get-WmiObject win32_service -ComputerName $pc
$schtask += schtasks.exe /query /s $pc /v /fo csv | ConvertFrom-Csv | where {$_.TaskName -ne “Taskname”}

So, what does all this do?  Breaking it down, the script gets a list of all computers that are joined to the domain.  It then take the output from the Get-ADComputer cmdlet and pipes it into the script block.  What’s happening here is the script checks that the computer is available by using the Test-Connection cmdlet.  If the computer is available, it queries the services and scheduled tasks of that computer and adds the output to an array.  Now we just need to output the values of each array.

$service | where {$_.StartName -eq $user} | Select-Object SystemName,DisplayName,Started,StartMode,StartName,State | Export-Csv -Path $env:USERPROFILE\Desktop\Services.csv”
$schtask | where {$_.“Run As User” -eq $user} | Select-Object Hostname,TaskName,Status,“Run As User” | Export-Csv -Path $env:USERPROFILE\Desktop\ScheduledTasks.csv”

The above sends the output of the script to CSV files on the current user’s desktop.  You may notice the Select-Object cmdlets in the middle.  Those are there to filter the output to only display pertinent information.  Without this, the CSV files would contain more detailed information regarding the services and scheduled tasks.  Now, you can copy all of the powershell code on this page and save it as Get-ServicesTasks.ps1.  Run this script if you need to find out what services and scheduled tasks are running as a specific user on your network.

If you have any questions, leave them in the comments.  Also, let me know how you would customize this script to fit your needs.