Powershell script to list scheduled tasks on remote systems

powershellpowershell-2.0scheduled-tasksscript

I want to write a PowerShell script that lists all Scheduled Tasks on remote systems, and includes the user account which will be used to run each task.

The local system is running Windows 7, with PowerShell 3.0. The remote systems range from Server 2003 to 2008 R2, with PowerShell versions from 2.0 to 3.0.

What PowerShell commands or functions can I use for this task?

Best Answer

I finally wrote a script that suits my needs. This script will 'scan' all the servers listed in AD, searching in the c:\Windows\System32\tasks folder for xml files. Then it will write the value of the UserID xml node of each file, in the final CSV file.

Not yet perfect but totally working to list all tasks of all servers, and log which user account is used to run them.

<#
.Synopsis
   PowerShell script to list all Scheduled Tasks and the User ID
.DESCRIPTION
   This script scan the content of the c:\Windows\System32\tasks and search the UserID XML value. 
   The output of the script is a comma-separated log file containing the Computername, Task name, UserID.
#>

Import-Module ActiveDirectory
$VerbosePreference = "continue"
$list = (Get-ADComputer -LDAPFilter "(&(objectcategory=computer)(OperatingSystem=*server*))").Name
Write-Verbose  -Message "Trying to query $($list.count) servers found in AD"
$logfilepath = "$home\Desktop\TasksLog.csv"
$ErrorActionPreference = "SilentlyContinue"

foreach ($computername in $list)
{
    $path = "\\" + $computername + "\c$\Windows\System32\Tasks"
    $tasks = Get-ChildItem -Path $path -File

    if ($tasks)
    {
        Write-Verbose -Message "I found $($tasks.count) tasks for $computername"
    }

    foreach ($item in $tasks)
    {
        $AbsolutePath = $path + "\" + $item.Name
        $task = [xml] (Get-Content $AbsolutePath)
        [STRING]$check = $task.Task.Principals.Principal.UserId

        if ($task.Task.Principals.Principal.UserId)
        {
          Write-Verbose -Message "Writing the log file with values for $computername"           
          Add-content -path $logfilepath -Value "$computername,$item,$check"
        }

    }
}

The output is a comma-separated file generated on your desktop, like this one :

> SRV028,CCleanerSkipUAC,administrator
> SRV029,GoogleUpdateTaskMachineCore,System
> SRV030,GoogleUpdateTaskMachineUA,System
> SRV021,BackupMailboxes,DOMAIN\administrator
> SRV021,Compress&Archive,DOMAIN\sysScheduler
Related Question