Forum Discussion

Kelemvor's avatar
Kelemvor
Icon for Expert rankExpert
8 months ago
Solved

Powershell: Expanding a variable inside single quotes to make an API call

Hi,

I’m trying to use Powershell to make an API call and pass in the SDT start/end time as a variable.  However, because the call has to be within single quotes, I can’t get it to expand the variable.

I have $now set to the epoch time of now and $later set to the epoch time two hours later.  I’m trying to make a call with something like:

'{"sdtType":1,"type":"DeviceSDT","deviceId":13771,"startDateTime":$now,"endDateTime":$later}'

Because the whole string is within a single quote, I can’t get PS to parse out the two variables and use their data.  I tried escaping the quotes and also using -f formatting, but can’t get anything to work.  Just wondering if anyone here knows how I can make this happen.

I tried swapping all the single and double quotes, which lets the Powershell work, but then the API fails because it requires double quotes to be surround the field names and won't accept single quotes.

Thanks.

  • It might be easier to build up the body of your API call in a variable and then pass it in.  So something like this:

    $body = '{"sdtType":1,"type":"DeviceSDT","deviceId":13771,"startDateTime":’ + $now + ‘,"endDateTime":’ + $later + ‘}'

    Then use the $body variable in your API call.

    Dave

4 Replies

  • Dave’s answer is still the best and suggested method. But just to throw this out, you can put single and double quotes in powershell strings. You will need to escape them. Meaning you use the back tick (`) mark (other languages use backslash (\) but powershell is different). So for example you can use:

    "{`"startDateTime`":$now,`"endDateTime`":$later}"

    It’s good for short strings or needing to compact one-liners, but can get messy if too long. Many cases your better off using a variable like above.

  • It might be easier to build up the body of your API call in a variable and then pass it in.  So something like this:

    $body = '{"sdtType":1,"type":"DeviceSDT","deviceId":13771,"startDateTime":’ + $now + ‘,"endDateTime":’ + $later + ‘}'

    Then use the $body variable in your API call.

    Dave

  • Nice.  I was able to get that to work.  Figured it was something not too complicated.

    Thanks!