Example of pulling a list of all Scheduled Tasks via PowerShell

Scenario: I have a bunch of scripts that run via Scheduled Tasks. I need to identify what account the scripts are executing under AND what script is running.

My 2 goals are:
1. Identify the security account used to run the script. I will then manually replace the older account with my newer account.

2. Identify a list of scripts and perform a search in each script to see if there are any references to an older server listed. I will then manually replace the value if the old server name is listed,


Resolution:

Goal 1: The $Tasks below will show me the script location AND which security account the script runs under.

#Identify a list of Tasks where I manually specify the task path for where I put my tasks:

        $Tasks = @()
        $Tasks = Get-ScheduledTask -TaskPath "\Custom Tasks\*" | Where state -ne "Disabled"
        $Tasks = Get-ScheduledTask -TaskPath "\Exchange Tasks\*" | Where state -ne "Disabled"
        $Tasks += Get-ScheduledTask -TaskPath "\"| Where state -ne "Disabled"


#Pull in the Info
        $Tasks = $tasks | where taskname -notlike user_feed* | Select TaskPath, TaskName,State,Author,@{Name="Run_As";Expression={$_.Principal | Select -expandproperty UserID}},@{Name="Script_Path";Expression={(($_.Actions | Select -expandproperty Arguments) -replace '-executionpolicy unrestricted -file ') -replace '-file '}}


#Display the Task Info

       $Tasks
        


Goal 2: For each script, perform a search to find a specific value. If the value is found, record it in $Results

#Identify Script Locations
        $scripts = @()
        $scripts = $Tasks.Script_Path       
        

#Find the value in each script and record it in $Results

        $str = "ExServer1"
        $results = @()
        $Scripts | %{
            $fn = $_
            $str | %{
                $s = $_
                $D = get-content $fn | Select-String $s
                If($D -ne $Null){
                    Write-Host "
                    Found String in File:  $fn" -ForegroundColor Cyan
                    $results += $fn
                    } #ENdIF
            }##end $Str loop
 }#End get-childitem loop



#Display the results
     $Results

Leave a comment