2

I need to make a POST call to a webserver which is validating usertype from cookies, I couldn't figure out how to add this cookies to my request.

$eth_config = Invoke-RestMethod -Method 'Post' -Uri $network_settings_url -Body $request_body  
CleanCoder540
  • 57
  • 1
  • 8

1 Answers1

6

Create a new WebRequestSession object:

$session = [Microsoft.PowerShell.Commands.WebRequestSession]::new()

Add cookies to session object:

$cookie = [System.Net.Cookie]::new('cookieName', 'value')
$session.Cookies.Add('https://domain.tld/', $cookie)

And then pass the session object to the -WebSession parameter of Invoke-RestMethod:

$eth_config = Invoke-RestMethod -Method 'Post' -Uri $network_settings_url -Body $request_body -WebSession $session

You could write a function to abstract away the creation of cookies:

function New-WebSession {
  param(
    [hashtable]$Cookies,
    [Uri]$For
  )

  $newSession = [Microsoft.PowerShell.Commands.WebRequestSession]::new()

  foreach($entry in $Cookies.GetEnumerator()){
    $cookie = [System.Net.Cookie]::new($entry.Name, $entry.Value)
    if($For){
      $newSession.Cookies.Add([uri]::new($For, '/'), $cookie)
    }
    else{
      $newSession.Cookies.Add($cookie)
    }
  }

  return $newSession
}

Then use like:

$session = New-WebSession -Cookies @{ 
  cookieName = 'Some cookie value'
  anotherCookie = 'some other value'
} -For $network_settings_url
$eth_config = Invoke-RestMethod -Method Post -Uri $network_settings_url -Body $request_body -WebSession $session
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • 1
    I don't why Microsoft official website does contain one example on this , I have gone through so many examples couldn't find one relevant – CleanCoder540 Oct 15 '21 at 17:00