Share via

Azure function - Powershell Date.AddDays not working

Madhu Rao 160 Reputation points
2025-06-13T02:13:25.02+00:00

Hi,

I have an Azure function that uses a date span to run a query. I am using the existing date and a (-ve) numeric value.

The below script works on my laptop.

$cldopsemailqrystrtdays = -7  # Set this to how many days back you want to go
$endtime = (Get-Date).Date    # Midnight today
$starttime = $endtime.AddDays($cldopsemailqrystrtdays)
Write-Output "Start Time: $starttime"
Write-Output "End Time:   $endtime"

I am passing an env: variable in Azure Function to pass on a numerical value that would be the start date of my query. The Azure function fails to recognise the start date.

$cldopsemailqrystrtdays=$env:cldopsemailqrystrtdays

$endtime = (Get-Date).Date
$starttime = ($endtime).AddDays($cldopsemailqrystrtdays)

$starttimemsg = $starttime
$endtimemsg = $endtime

Write-Host "$starttime - $endtime"

Thanks in advance.

Azure Functions
Azure Functions

An Azure service that provides an event-driven serverless compute platform.


Answer accepted by question author

RChotu 3,210 Reputation points Microsoft External Staff Moderator
2025-06-16T02:45:11.2866667+00:00

Hi @Madhu Rao ,

Initially I have environment variable as below:

image

Then used blow code that works:

using namespace System.Net

param($Request, $TriggerMetadata)
Write-Host "Hello Rithwik"
$cldopsemailqrystrtdays = $env:cldopsemailqrystrtdays -as [int]
$endtime = (Get-Date).Date
$starttime = $endtime.AddDays($cldopsemailqrystrtdays)
Write-Host "Rithwik, the Start Time is $starttime"
Write-Host "Rithwik, the End Time is   $endtime"
$rithout = @{
    startTime = $starttime.ToString("yyyy-MM-ddTHH:mm:ssZ")
    endTime   = $endtime.ToString("yyyy-MM-ddTHH:mm:ssZ")
}
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $rithout | ConvertTo-Json -Depth 3
})

Output:

enter image description here

You can also use below code, which gives expected results:

$cldopsemailqrystrtdaysRaw = $env:cldopsemailqrystrtdays
$cldopsemailqrystrtdays = [int]$cldopsemailqrystrtdaysRaw

If this answer was helpful, please click "Accept the answer" and mark Yes, as this can help other community members.

enter image description here

If you have any other questions or are still experiencing issues, feel free to ask in the "comments" section, and I'd be happy to help.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.