Home > Software engineering >  Pass Dates Range in PowerShell
Pass Dates Range in PowerShell

Time:06-23

I'm connecting to an API and in the Body I need to specify the date range for the data. Is it possible to make this dynamic so it will show today's date instead of the static
"2022-06-10T16:30:34.516Z", as shown below?

$body= @"
{"sort":[{"field":"createdOn","direction":"desc"}],"filter":{"operator":"gt","field":"createdOn","value":"2022-06-10T16:30:34.516Z"},"fields":[],"page":{"length":100,"offset":0}}
"@

CodePudding user response:

Something like that should do it.

Basically you want to convert the json to a PSObject, edit the value you are interested in and convert it back.

The conversion process take care of escaping characters as needed.

Example


$body = @"
{"sort":[{"field":"createdOn","direction":"desc"}],"filter":{"operator":"gt","field":"createdOn","value":"2022-06-10T16:30:34.516Z"},"fields":[],"page":{"length":100,"offset":0}}
"@


# Convert the json to a PSObject to edit it
$jsonObj = $body | ConvertFrom-Json

# Set the date
$jsonObj.filter.value = Get-Date

# Your new Json.
$body = $jsonObj | ConvertTo-Json -Compress

CodePudding user response:

I'm assuming you're constructing the JSON string yourself, so you can use PowerShell's string interpolation:

$body= @"
... "value":"$([datetime]::UtcNow.ToString('o'))"} ...
"@

Note the use of $(...), the subexpression operator, which is required to embed the value of expressions and even whole statements inside an expandable (double-quoted) string ("..."), including in the here-string variant being used here.

Note that [datetime]::UtcNow.ToString('o') produces a string such as
'2022-06-10T16:30:34.5161234Z', i.e. a format with 4 additional decimal places compared to the example in your question.

  • Related