0

I am trying to calculate the time elapsed for a task in Azure Pipeline using PowerShell task on inline mode. Simplified setup looks like in the image as attached. The inline code is mentioned below. I am getting below specified error.

Calculating Elapsed Time...
Cannot find an overload for "op_Subtraction" and the argument count: "2".
At D:\a\_temp\ba6b91f4-ef47-4a51-8088-efc6bcda310d.ps1:5 char:1
+ $duration_min = $end_time - $start_time
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest
 
##[error]PowerShell exited with code '1'.

What is the right approach to measure the time elapsed for a build task?

Pipeline Setup:

enter image description here

Code in Get Start Time inline powershell task:

$start_time = Get-Date
Write-Host "Scanning Start Timestamp: $($start_time)"

Code in Calculate Elapsed Time inline powershell task:

Write-Host "Calculating Elapsed Time..."
$end_time = Get-Date
$duration_min = $end_time - $start_time
Write-Host ("Total Time Elapsed in Minutes: ", $duration_min.TotalMinutes)
Rajesh Swarnkar
  • 601
  • 1
  • 6
  • 18
  • Your code works fine for me. Can you try to typecast your variables like `[timespan]$duration_min = [datetime]$end_time - [datetime]$start_time` – Vivek Kumar Singh Dec 23 '21 at 10:07
  • Ok, good idea. Did you referred both variables `$start_time` and `$end_time` from same PowerShell tasks? Because I am getting `Cannot convert null to type "System.DateTime"` after adding typecast. – Rajesh Swarnkar Dec 23 '21 at 11:22
  • Yes, I did refer to them from the same console. What you can do is you can initialise the variables `$end_time` and `$start_time` as `[datetime]$end_time = Get-Date` and `[datetime]$start_time= Get-Date`, in order to avoid populating them as `$null`. – Vivek Kumar Singh Dec 23 '21 at 13:12

1 Answers1

0

Variables between the tasks are independent. To pass the values between the tasks, we can use the pipeline variables. In your setup, go to Variables tab and create a new variable - say scan_start_time.

In the "Get Start Time" task add another line

Write-Output "##vso[task.setvariable variable=scan_start_time]$($start_time)"

Then in the "Calculate Elapsed Time" task

$start_time = "$(scan_start_time)"
amit_g
  • 30,880
  • 8
  • 61
  • 118