NGloudemans
NGloudemans

Reputation: 3

How to make multi-line uri using invoke-webrequest in Powershell

I'm trying to concatenate my uri in this invoke so that I can have each variable on a separate line. That way I can make changes easier and don't have to search as hard. I was able to do this in a bash script, but am at a loss for how to do this in Powershell.

Line as follows:

Invoke-WebRequest -Uri (beginning of url)?date=$date"&"time=$time"&"name=$env:computername"&"loginid=$env:username"&"sn=$serialnumber"&"ipaddr=$ipaddr"&"verb=profileclear

Thanks!

Upvotes: 0

Views: 1244

Answers (3)

AdminOfThings
AdminOfThings

Reputation: 25001

I would create an array of variable strings, join them, and build a uri:

$variables = "date=$date",
"time=$time",
"name=$env:computername",
"loginid=$env:username",
"sn=$serialnumber",
"ipaddr=$ipaddr",
"verb=profileclear"

$uri = [System.UriBuilder]::new('https://contoso.com')
$uri.Query = $variables -join '&'

Invoke-WebRequest -Uri $uri.ToString()

Upvotes: 1

Kage
Kage

Reputation: 486

I think the easiest way of achieving this would be like this:

$uri = "Https://something.somewhere/?" +
    "date=$date&" + 
    "time=$time&" + 
    "name=$env:computername&" + 
    "loginid=$env:username&" + 
    "sn=$serialnumber&" + 
    "ipaddr=$ipaddr&" + 
    "verb=profileclear" 

Invoke-WebRequest -Uri $uri

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

One option is to store the query parameters in an ordered dictionary and construct the URL from that:

$parameters = [ordered]@{
  date     = $date
  time     = $time
  name     = $env:computername
  loginid  = $env:username
  sn       = $serialnumber
  ipaddr   = $ipaddr
  verb     = 'profileclear'
}

$baseURI = 'https://host.fqdn/path'

# Construct full URI string from base URI + parameters
$queryString = @($parameters.GetEnumerator() |ForEach-Object {
  '{0}={1}' -f $_.Key,$_.Value
}) -join '&'

$URI = '{0}?{1}' -f $baseURI,$queryString

Invoke-WebRequest -Uri $URI

Upvotes: 0

Related Questions