Wednesday, January 13, 2016

Using PowerShell to Query for Scheduled Tasks

For those of you with older systems that don't support the newer Get-ScheduledTask cmdlet, you can still use PowerShell to pull scheduled tasks making use of schtasks.exe via the Invoke-Command cmdlet.

One trick to using schtasks.exe with PowerShell is to use the /fo csv option which - surprise, surprise - forces the command to output in CSV format. Luckily PowerShell has the ConvertFrom-Csv cmdlet which works fairly seamlessly.

Below is an example of retrieving scheduled tasks from a computer named "SERV01" using Invoke-Command. The command to remotely execute is stored in the $ScriptBlock variable.

$ScriptBlock = { schtasks.exe /query /s localhost /V /FO CSV | ConvertFrom-Csv }
$ComputerList = Get-ADComputer -Filter "Name -like 'SERV01'"
foreach ($Computer in $ComputerList) {
    Invoke-Command -ComputerName $Computer.Name -ScriptBlock $ScriptBlock
}

No comments:

Post a Comment