Search code examples
regexwindowscmdfindstr

How do I filter schtasks output with regular expressions in Windows CMD to return blocks of results containing "Schedule Type: Daily"?


How do I filter schtasks output with regular expressions in Windows CMD to return blocks of results containing "Schedule Type: Daily"?

I want to be able to filter the blocks of results containing "Schedule Type: Daily" with something like this:

schtasks /query /fo LIST /v | findstr /r "\n\n[.|\n]*Daily[.|\n]*\n\n"

So here is an example of one result block I would like the command to return: enter image description here


Solution

  • Here is a way using the more complete regex capability in PowerShell to find the Schedule Type: Daily tasks.

    & schtasks.exe /query /fo LIST /v |
        ForEach-Object {
            if ($_ -match '^TaskName:\s*(.*)$') { $CurrentTask = $Matches[1] }
            if ($_ -match '^Schedule Type:\s*Daily\s*$') { $CurrentTask }
        }
    

    If you must run this from cmd.exe, the following might be used.

    @powershell.exe -NoLogo -NoProfile -Command ^
        "& schtasks.exe /query /fo LIST /v |" ^
            "ForEach-Object {" ^
                "if ($_ -match '^TaskName:\s*(.*)$') { $CurrentTask = $Matches[1] }" ^
                "if ($_ -match '^Schedule Type:\s*Daily\s*$') { $CurrentTask }" ^
            "}"