简体   繁体   中英

Powershell Object reference not set to an instance of an object

The below loop forms part of a Powershell script that loops through Windows Tasks Schedules and then send an email with the statue and duration etc. However, when it executes the below loop I then receive the erorr:

New-TimeSpan : Cannot bind parameter 'Start' to the target. Exception setting "Start": "Object reference not set to an instance of an object."

This is the loop:

foreach ($Task in $Tasks){
    switch -Regex ($Task){
        {$DailyTasks -contains $Task}{
            $TaskRunTime = (Get-ScheduledTaskInfo "$Task").LastRunTime
            $Difference = (New-TimeSpan -Start $TaskRunTime).TotalHours
            $IntervalCheck = 12

            switch -Regex ($Difference){
                {($Difference -gt "$IntervalCheck")}{
                    $Status = "BAD"

                    $EmailTemp = @"
    <tr>
        <td class="colorm">$Task</td>
        <td class="colorr">$Status</td>
    </tr>
"@
                }
                {$Difference -lt "$IntervalCheck"}{
                    $Status = "OK"

                    $EmailTemp = @"
    <tr>
        <td class="colorm">$Task</td>
        <td>$Status</td>
    </tr>

What am I missing?

it's possible your task has never run before, so $TaskRunTime is $null? In which case you need to handle a possible null value.

I'm not sure if your $Task is a task object or just a string.... if it's just a string you will have to run to obtain last run time:

$TaskRunTime = (Get-ScheduledTask $Task | Get-ScheduledTaskInfo).LastRunTime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM