Skip to main content

Find Scheduled Tasks That Run as Privileged or Stored-Password Accounts on Windows Servers with PowerShell

A read-only PowerShell audit that finds scheduled tasks running as domain admins or with stored passwords, and how to act on them safely.

Person holding anonymous mask near servers, hinting at cybersecurity and hacking themes.

Advertising disclosure: this article includes partner links. KBY may earn a commission if you sign up or buy through one, at no extra cost to you. How we make money.

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

Run Get-ScheduledTask against each server with -CimSession, read each task’s Principal, and flag three things: a LogonType of Password (Windows needed the account’s password when the task was registered), a RunLevel of Highest on an account where that setting still means something, and a run-as account that is a member of Domain Admins. The audit itself changes nothing.

Export every flagged task’s before anyone touches it, because a password-logon task cannot be put back without its password. Treat the report as incomplete rather than clean, too: MITRE ATT&CK documents attackers hiding tasks from the usual enumeration tools.

#Why it matters which account a task runs as

Scheduled tasks are the place where old service accounts go to live. A copy job set up years ago, a vendor’s licence check, a nightly export somebody wrote with their own admin account on a Friday afternoon: each one is registered with a principal, and that principal keeps working long after people forget the task exists.

When the account is a domain administrator and the task logs on with a password, every server carrying that task is also carrying the means to run code as a domain administrator. Each of those servers then needs the protection you would give the account itself.

MITRE ATT&CK lists scheduled tasks (T1053.005) under execution, persistence and privilege escalation. Its description notes that Task Scheduler can be abused to run a process under the context of a specified account such as SYSTEM, and to run code remotely as part of lateral movement. Its mitigation for user account management is to limit privileges so only authorised administrators can create scheduled tasks on remote systems. Knowing which tasks already run as powerful accounts is the starting point for either.

The other reason is operational. Microsoft’s Task Scheduler documentation says tasks registered with a password or S4U logon will only launch if the account holds the Log on as a batch job right. When a clean-up project removes that right, or an account is disabled because “nobody uses it”, the tasks that quietly depended on it stop. An inventory tells you which tasks will break before you make either change.

#Under the hood of a task principal

Every task has a principal: the security context its actions run in. The Principal element in the task XML carries a UserId or a GroupId, a LogonType and a display name, and the scripting Principal object adds a RunLevel. New-ScheduledTaskPrincipal exposes the same fields as parameters, and its documentation lists the accepted logon types: None, Password, S4U, Interactive, Group, ServiceAccount and InteractiveOrPassword.

The logon type is what tells you whether a credential is involved. From the TASK_LOGON_TYPE reference:

  • Password: the account logs on with a password, which must be supplied when the task is registered.
  • S4U: Task Scheduler logs the account on with Service For User. No password is stored, and the task has no access to the network or to encrypted files.
  • Interactive: the user must already be logged on, and the task runs only in that session.
  • ServiceAccount: the task runs as Local System, Local Service or Network Service.
  • Group: the task is activated for members of the group named in GroupId.
  • InteractiveOrPassword: on current Windows versions Microsoft describes it as not in use and identical to Password. On older releases it tried the interactive token first and fell back to the password.

Because S4U is documented as storing no password, and the password type needs one at registration, it is reasonable to treat every Password and InteractiveOrPassword task as one where Windows holds a credential for that account on that server. That is an inference from the two definitions rather than a sentence Microsoft writes, but it is the right working assumption for a security review.

The run level is the second axis. Highest runs the actions with the account’s highest privileges; Limited runs them as a least-privileged user (LUA).

Microsoft’s Principal.RunLevel reference adds two exceptions that matter for the audit: the setting is ignored when the task is registered as the built-in Administrator, Local System or Local Service, and it is ignored entirely when User Account Control is turned off. So a Highest flag on a Local System or Local Service task tells you nothing.

The script below skips Highest on every ServiceAccount task to keep the report short. Microsoft’s exception does not name Network Service, so if any Network Service tasks are set to Highest, look at those separately.

Rendering diagram...

#Setting up the inventory across your servers

Run this from an admin workstation or management server with the ActiveDirectory module installed, in an elevated session. You need to be able to read the tasks on each target: Microsoft’s security model for tasks lets members of the local Administrators group or SYSTEM read any task, while ordinary users see only the tasks they created. Start with a short list of non-production servers to confirm the output shape, then widen it.

  1. Put the server names in a text file, one per line, for example C:\audit\servers.txt.
  2. Collect the members of Domain Admins, including nested members. Get-ADGroupMember -Recursive returns every member in the group’s hierarchy that does not itself contain child objects, so nested groups are expanded to the users and accounts inside them.
  3. Run the inventory script below. It connects to each server with Get-ScheduledTask -CimSession, which the cmdlet documentation describes as running the command on a remote computer when given a computer name or session object.
  4. Open the CSV and sort by the Flag column.

Following along? Tap a step’s number to tick it off.

1$servers    = Get-Content -Path 'C:\audit\servers.txt'
2$domainAdmins = Get-ADGroupMember -Identity 'Domain Admins' -Recursive |
3    ForEach-Object { $_.SamAccountName }
4
5$report = foreach ($server in $servers) {
6    try {
7        $tasks = Get-ScheduledTask -CimSession $server -ErrorAction Stop
8    }
9    catch {
10        [pscustomobject]@{ Server = $server; TaskPath = ''; TaskName = ''; UserId = ''
11            GroupId = ''; LogonType = ''; RunLevel = ''; State = ''
12            Flag = "NotReached: $($_.Exception.Message)" }
13        continue
14    }
15    $flaggedHere = 0
16    foreach ($task in $tasks) {
17        $p = $task.Principal
18        $flags = @()
19        if ($p.LogonType -in 'Password', 'InteractiveOrPassword') { $flags += 'StoredPassword' }
20        if ($p.RunLevel -eq 'Highest' -and $p.LogonType -ne 'ServiceAccount') { $flags += 'Highest' }
21        $account = ($p.UserId -split '\\')[-1]
22        if ($account -and $domainAdmins -contains $account) { $flags += 'DomainAdmin' }
23        if ($flags.Count -gt 0) {
24            $flaggedHere++
25            [pscustomobject]@{ Server = $server; TaskPath = $task.TaskPath; TaskName = $task.TaskName
26                UserId = $p.UserId; GroupId = $p.GroupId; LogonType = $p.LogonType
27                RunLevel = $p.RunLevel; State = $task.State; Flag = ($flags -join ',') }
28        }
29    }
30    if ($flaggedHere -eq 0) {
31        [pscustomobject]@{ Server = $server; TaskPath = ''; TaskName = ''; UserId = ''
32            GroupId = ''; LogonType = ''; RunLevel = ''; State = ''; Flag = 'NoneFlagged' }
33    }
34}
35$report | Export-Csv -Path 'C:\audit\task-principals.csv' -NoTypeInformation

A few choices in that script are deliberate. -ErrorAction Stop turns a failed connection into a terminating error so the catch block records the server as not reached, instead of the server simply being missing from the report, and a server that was reached but had nothing to flag gets one NoneFlagged row, so every server in the list leaves a trace.

The account match strips any domain prefix with -split and compares the bare name with -contains, which is case-insensitive by default; if you have accounts with the same name in different domains, compare on the full name instead. A principal stored as a SID or in user@domain form will not match a bare account name, so read the UserId column for those by eye.

Domain Admins is only the starting point: add Enterprise Admins and any other group you treat as tier zero to the same list. The script does not filter out tasks by folder, so tasks that ship with Windows appear too if they match; they are worth seeing once before you decide to exclude any.

This follows the same pattern as finding expiring certificates on Windows servers with PowerShell: read-only collection across many servers into one CSV, with unreachable servers listed rather than dropped.

Close-up of a to-do list next to a computer keyboard on a desk.
Photo by Walls.io on Pexels

#
Back up every flagged task before anyone acts on it

Export-ScheduledTask exports a task’s definition as an XML string. Save one file per flagged task, named after the server, the task’s folder and the task, to a folder only administrators can read. Including the folder stops two tasks with the same name in different folders overwriting each other’s backup.

1foreach ($row in ($report | Where-Object { $_.TaskName })) {
2    $folder = $row.TaskPath -replace '\\', '_'
3    $file = 'C:\audit\backup\{0}{1}{2}.xml' -f $row.Server, $folder, $row.TaskName
4    Export-ScheduledTask -CimSession $row.Server -TaskName $row.TaskName -TaskPath $row.TaskPath |
5        Out-File -FilePath $file
6}

The Principal element in the export has fields for the user or group, the logon type and a display name, and none for a password. That is the single most important fact for the rest of this article: Microsoft’s TASK_LOGON_TYPE reference says the password for a password-logon task must be supplied at registration time, so restoring one of these tasks from its XML needs the password again. Find out who holds it before you change anything.

#
What to do with each finding

Treat the report as a list of conversations, not a list of changes. For each flagged task, find the owner and decide which of these applies:

  • Nobody owns it and it has not run for a long time. Check Get-ScheduledTaskInfo for the task’s run-time information, confirm with the server owner, then disable it rather than delete it.
  • It needs a domain account and network access. Plan a move to a group managed service account (gMSA), which Microsoft lists as supporting tasks run by Task Scheduler. Microsoft’s gMSA management guide does not give the command for assigning one to an existing task, so test that change on a copy of the task in a lab and follow your own change process for it.
  • It only works on the local server. S4U stores no password, but it also has no access to the network or to encrypted files, so check what the task reads and writes before considering it.
  • The script the task runs has a password of its own written into it. That is a separate problem from the task’s logon, and moving passwords out of scheduled PowerShell scripts with SecretManagement and SecretStore covers it.
  • It runs as a domain administrator. Whatever else you decide, the account should not be a domain administrator. That is a separate change to the account, with its own owner and testing.

Disabling is the one change this article walks through, because it has a clean way back:

1Get-ScheduledTaskInfo -CimSession 'SRV-APP01' -TaskName 'NightlyExport' -TaskPath '\'
2Disable-ScheduledTask -CimSession 'SRV-APP01' -TaskName 'NightlyExport' -TaskPath '\'

Before that second line runs, three things should be true: the XML export for that task exists, the server’s owner has agreed, and you have a date by which, if nobody complains, the task will be reviewed again. Disable-ScheduledTask changes the task’s state and leaves its definition registered, so Enable-ScheduledTask with the same name and path brings it back.

If you are preparing a gMSA, Microsoft’s procedure has its own preconditions. A Key Distribution Services root key must exist in the domain, the gMSA is created with New-ADServiceAccount and a -PrincipalsAllowedToRetrieveManagedPassword group containing the servers, and it is installed on each host with Install-ADServiceAccount.

Microsoft notes that the password change interval can only be set when the gMSA is created. Test readiness on the host with Test-ADServiceAccount, which returns True when the account can authenticate and reach the domain with its current credentials.

#Check it worked before you trust the report

An inventory is only useful if you know what it missed. Before you send the CSV to anyone, check these:

  1. Every server in servers.txt appears in the report at least once: with flagged tasks, with a NotReached row or with a NoneFlagged row. A server that is absent was never processed, usually because of a typo or blank line in the list.
  2. Pick one flagged task and compare its row with the XML you exported for it. The UserId or GroupId and the LogonType inside the Principal element should match the CSV exactly.
  3. Pick one known password-logon task you already know about, such as a job your own team set up, and confirm it appears with the StoredPassword flag. If it does not, the run lacked rights on that server.
  4. For every task you disabled, run Get-ScheduledTask for that name and path and confirm State is Disabled.

Success looks like this: a CSV covering every listed server, an XML backup for every flagged task, and a named owner against each DomainAdmin row.

Close-up of tower servers in a data center with blue and red lighting.
Photo by panumas nikhomkhai on Pexels

#What goes wrong when you act on the findings

The audit is safe. The follow-up work is where things break.

  • A task restored from its XML will not register, or registers but fails at its next run. A password-logon task needs its password at registration, and the export does not contain it. Supply it with -User and -Password on Register-ScheduledTask, or restore the task with the owner present.
  • Tasks stop after a user rights clean-up. Password and S4U tasks only launch when the account holds Log on as a batch job. Microsoft’s policy reference gives the default holders on member servers as Administrators, Backup Operators and Performance Log Users, and notes that the Add Scheduled Task Wizard grants the right automatically when a task is set up with a user name and password. Removing an account from Administrators can remove its only route to that right.
  • A task moved to S4U runs but its work fails. S4U has no network access, so any task that writes to a share or calls another server fails after the change.
  • The Highest column suggests elevation that is not happening. If UAC is off on a server, Windows ignores the run level for every task there, so the flag overstates the change in privilege. It does not make a domain admin account any less powerful.
  • The report has gaps you cannot see. MITRE ATT&CK documents attackers hiding tasks from schtasks /query and Task Scheduler by deleting the task’s security descriptor value in the registry, which needs SYSTEM rights, and by altering other task metadata in the registry. A clean report from this script is not evidence that a server has no hostile tasks; that question belongs with your endpoint detection tooling.
  • Some servers come back as NotReached. The error text in the row says why. Treat those servers as not audited, not as clean.

#Least privilege for the audit and for the tasks

The audit needs to read tasks on every server, and Microsoft’s model gives that to local administrators. Run it from a privileged admin workstation, with an account that is an administrator on member servers but not a domain administrator, and keep the CSV and the XML exports in a folder with the same restriction. The report is a map of which servers hold credentials for which powerful accounts, which is exactly what an attacker would want.

For the tasks themselves, the documented options rank roughly like this, from least to most exposure: a built-in service account or S4U where the work is local, a gMSA where the work needs a domain identity, and a named user account with a password only where nothing else is possible. A domain administrator account should not appear in that last group.

Where a task must run elevated, record why in the task’s description so the next audit can tell a deliberate setting from an accident. Who can create tasks matters as much as which accounts they run as. MITRE’s mitigation is to make sure only authorised administrators can create scheduled tasks on remote systems; this inventory, run regularly, is how you notice when that has not held.

#How to roll back a task you changed

Every state change in this article has a way back, and each depends on the backup taken earlier:

  1. A task you disabled: run Enable-ScheduledTask -CimSession <server> -TaskName <name> -TaskPath <path>, then confirm with Get-ScheduledTask that its State is no longer Disabled. The task was never unregistered, so nothing else needs restoring.
  2. A task that was changed or removed during follow-up work: register it again from the export with Register-ScheduledTask -CimSession <server> -Xml (Get-Content -Path <file> -Raw) -TaskName <name> -TaskPath <path> -User <account> -Password <password>. Microsoft’s reference notes the password is ignored for the well-known system accounts, so it is only needed for user accounts. If you do not have the password, do not remove the original task until you do.
  3. A gMSA you installed on a host and no longer need there: Microsoft’s procedure is Uninstall-ADServiceAccount -Identity <gMSAName> on that host.

When the first pass is done, the useful state is a report you can rerun: the same script on a schedule of its own, compared month to month, so a new password-logon task or a new domain administrator principal shows up as a change rather than waiting for the next project. Settle who reads that comparison before you schedule it.

About this page

Credited to

Dates

Published

Sources

This page lists no external sources.

Corrections

No corrections are listed for this page. Some review sweeps corrected pages without naming each one; those are in the corrections log.

Found this useful? Follow KBY for more like it.

Reader Interaction

Comments

Add a thoughtful note on Find Scheduled Tasks That Run as Privileged or Stored-Password Accounts on Windows Servers with PowerShell. Comments are checked for spam and held for moderation before appearing.

Loading comments...

More from KBY that goes with this article.

Discover more

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Engineering insights, direct to you.

Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.