r/PowerShell • u/BWMerlin • Feb 16 '26
Solved Having trouble escaping Uri
I will keep it simple.
I have the following line which I am having trouble escaping. The code does run but it is not escaped properly.
$report = Invoke-RestMethod -Method Get -Uri '`"'$url"'/xapi/v1/ReportAbandonedQueueCalls/Pbx.GetAbandonedQueueCallsData(periodFrom="$sevenDaysAgo",periodTo="$today",queueDns="$queue",waitInterval="0")' -Headers $headers -VerboseThe relevant parts of my code are the following.
$url = "https://myurl.com.au:443"Copilot code (I hate myself for it but was getting a whole lot of no where).
function Get-EncodedUtcTimestamp {
[CmdletBinding()]
param(
[int]$OffsetHours = 10, # +10:00 offset
[int]$DaysAgo = 0, # 0 = today, 7 = seven days ago, etc.
[int]$Hour = 0,
[int]$Minute = 0,
[int]$Second = 0
)
$tzOffset = [TimeSpan]::FromHours($OffsetHours)
$nowInTz = [DateTimeOffset]::UtcNow.ToOffset($tzOffset)
$targetDate = $nowInTz.AddDays(-$DaysAgo)
# Build the target local time in the specified offset
$targetInTz = [DateTimeOffset]::new(
$targetDate.Year, $targetDate.Month, $targetDate.Day,
$Hour, $Minute, $Second, $tzOffset
)
# Convert to UTC and format with URL-encoded colons
$targetInTz.ToUniversalTime().ToString("yyyy-MM-dd'T'HH'%3A'mm'%3A'ss.fff'Z'")
}
# --- Calls ---
# Today in +10:00 at 23:59 -> UTC, URL-encoded
$today = Get-EncodedUtcTimestamp -OffsetHours 10 -DaysAgo 0 -Hour 23 -Minute 59
# 7 days ago in +10:00 at 00:00 -> UTC, URL-encoded
$sevenDaysAgo = Get-EncodedUtcTimestamp -OffsetHours 10 -DaysAgo 7 -Hour 0 -Minute 0I should end up with something that looks like the following.
https://myurl.com.au:443/xapi/v1/ReportAbandonedQueueCalls/Pbx.GetAbandonedQueueCallsData(periodFrom=2026-02-08T14%3A00%3A00.000Z,periodTo=2026-02-16T13%3A59%3A00.000Z,queueDns='queueNumberHere',waitInterval='0')
9
Upvotes
4
u/BetrayedMilk Feb 16 '26 edited Feb 16 '26
Use URIs from .NET to more easily combine your url string and then use UrlEncode if needed.
https://learn.microsoft.com/en-us/dotnet/api/system.uri?view=net-10.0
https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.urlencode?view=net-10.0
These URI constructors specifically:
https://learn.microsoft.com/en-us/dotnet/api/system.uri.-ctor?view=net-10.0#system-uri-ctor(system-string)
https://learn.microsoft.com/en-us/dotnet/api/system.uri.-ctor?view=net-10.0#system-uri-ctor(system-uri-system-string)
1
u/AdeelAutomates Feb 17 '26
Is this what you are asking for?
Use double quotes with
$( $variable )to inject your data:Output:
2
u/purplemonkeymad Feb 16 '26
You used single quotes, use double quotes if you want variables to substituted inside a string. IRM will automatically url encode for you, so you can just use $date.ToString('s')
1
u/PinchesTheCrab Feb 16 '26 edited Feb 16 '26
I hate APIs like this. The SCCM api has infuriating syntax with weird nested expressions that require escaping in the URL path. Anyway, a here-string may help:
0
u/[deleted] Feb 16 '26
[deleted] — view deleted comment