添加 cookie 以调用 Rest-Method Powershell

Adding cookies to InvokeRest-Method Powershell

我需要对网络服务器进行 POST 调用,该服务器正在根据 cookie 验证用户类型,但我不知道如何将此 cookie 添加到我的请求中。

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

创建一个新的 WebRequestSession 对象:

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

将 cookie 添加到会话对象:

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

然后将session对象传递给Invoke-RestMethod-WebSession参数:

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

您可以编写一个函数来抽象化 cookie 的创建:

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
}

然后像这样使用:

$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