How can I properly escape a URI in PowerShell?

0
9
Asked By CuriousCoder92 On

I'm struggling with escaping a URI in my PowerShell script. My code runs but the escaping isn't working as expected. Here's the line that I'm having trouble with:

```
$report = Invoke-RestMethod -Method Get -Uri '`"'$url"'/xapi/v1/ReportAbandonedQueueCalls/Pbx.GetAbandonedQueueCallsData(periodFrom="$sevenDaysAgo",periodTo="$today",queueDns="$queue",waitInterval="0")' -Headers $headers -Verbose
```

The relevant part of my code is as follows:

```
$url = "https://myurl.com.au:443"
```

I used a function to get the current UTC timestamp, and I want the URL to look something like this once properly escaped:

```
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')
```

Any tips or solutions?

4 Answers

Answered By CodeNinja99 On

If you want to inject variables, switch to double quotes and use `$( $variable )`. Here’s a quick example:

```
$sevenDaysAgo = "2026-02-08T14%3A00%3A00.000Z"
$today = "2026-02-16T13%3A59%3A00.000Z"
$queue = "queueNumberHere"
$uri = "https://myurl.com.au:443/xapi/v1/ReportAbandonedQueueCalls/Pbx.GetAbandonedQueueCallsData(periodFrom=$($sevenDaysAgo),periodTo=$($today),queueDns=$($queue),waitInterval='0')"
```
This should give you the properly formatted output you're looking for!

Answered By ScriptingSage On

Instead of single quotes, try using double quotes around your string. This way, variables like `$sevenDaysAgo` will be substituted correctly. Also, remember that Invoke-RestMethod handles URL encoding automatically, so just format your dates with `$date.ToString('s')` and it should work!

Answered By API_Advocate On

Yeah, dealing with APIs can be a hassle! You can create a here-string that allows for cleaner formatting. For example, you could use:

```powershell
$template = @'
'https://myurl.com.au:443/xapi/v1/ReportAbandonedQueueCalls/Pbx.GetAbandonedQueueCallsData(periodFrom={0},periodTo={1},queueDns='{2}',waitInterval='0')'
'@
$template -f $today, $sevenDaysAgo, 'queueNumberHere'
```
This makes it easier to manage your variables without worrying about escaping too much.

Answered By TechGuru56 On

You might want to use .NET's capabilities for building and escaping your URI. This can simplify your code a lot! Check out the documentation for the System.Uri class to combine your URL parts easily. Plus, look at the HttpUtility.UrlEncode method to handle any escaping you need. It can save you from a lot of headaches!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.