Skip to the main content.

Unlocking the Power of PowerShell: Tips for Success

How To Use Web Services in PowerShell - Advanced Options

In the previous parts we looked at the basic tasks Invoke-WebRequest and Invoke-RestMethod perform, and how both differ. Now we will dive into more advanced options.

When you’re really into web services, then you may have sophisticated requirements, such as needing to authenticate, provide tokens, or maintain persistence between multiple calls.

All this is possible with both cmdlets; however, it is not trivial and involves a deeper understanding of what a particular web service needs from you to be happy.

Understanding Advanced Options

One great way to learn is by using the Chrome browser and its developer tools to have Chrome write an initial PowerShell script for you.

You can then investigate this script to learn more about the advanced options. Start by navigating to any website in Chrome. Ideally, the website should have a form or allow you to log in. Then do this:

  1. Press F12 to open the developer tools. A side pane opens in your browser. Click the “Network” tab. You will now see all web requests the browser performs. You may want to click the “clear” icon to clear the list.
  2. Click the link that you want to automate, or fill in the form and press the button that is required to proceed. In the developer tools list, you can see the web requests this action generates.
  3. Identify the web request that is most likely performing your authentication, or whatever action you intended to trigger.
  4. Right-click the action in the list, and in the context menu, choose “Copy” > “Copy as PowerShell”

Chrome has now automatically written a PowerShell script for you that illustrates how you can mimic in PowerShell the web action that the browser just performed.

Switch to your PowerShell editor and paste the auto-generated code from the clipboard. It may look similar to this:


$session.Cookies.Add((New-Object System.Net.Cookie("datr", "c3KeZ80pw3J2euC0ctQH6Yrk", "/", ".facebook.com")))
$session.Cookies.Add((New-Object System.Net.Cookie("wd", "811x593", "/", ".facebook.com")))
$session.Cookies.Add((New-Object System.Net.Cookie("dpr", "3", "/", ".facebook.com")))
Invoke-WebRequest -UseBasicParsing -Uri "https://www.facebook.com/login/?privacy_mutation_token=eyJ0eXBlIjowLCJjcmVhdGlvbl90aW1lIjoxNzM4NDM3MjQ3LCJjYWxsc2l0ZV9pZCI6MzgxMjI5MDc5NTc1OTQ2fQ%3D%3D&next" `
-Method "POST" `
-WebSession $session `
-Headers @{
"authority"="www.facebook.com"
  "method"="POST"
  "path"="/login/?privacy_mutation_token=eyJ0eXBlIjowLCJjcmVhdGlvbl90aW1lIjoxNzM4NDM3MjQ3LCJjYWxsc2l0ZV9pZCI6MzgxMjI5MDc5NTc1OTQ2fQ%3D%3D&next"
  "scheme"="https"
  "accept"="text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
  "accept-encoding"="gzip, deflate, br, zstd"
  "accept-language"="de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7"
  "cache-control"="max-age=0"
  "dnt"="1"
  "origin"="https://www.facebook.com"
  "priority"="u=0, i"
  "referer"="https://www.facebook.com/?locale=de_DE"
  "sec-ch-ua"="`"Not A(Brand`";v=`"8`", `"Chromium`";v=`"132`", `"Google Chrome`";v=`"132`""
  "sec-ch-ua-mobile"="?0"
  "sec-ch-ua-platform"="`"Windows`""
  "sec-fetch-dest"="document"
  "sec-fetch-mode"="navigate"
  "sec-fetch-site"="same-origin"
  "sec-fetch-user"="?1"
  "upgrade-insecure-requests"="1"
} `
-ContentType "application/x-www-form-urlencoded" `
-Body "jazoest=2965&lsd=AVqxMFYEqs0&email=someone%40somewhere.com&login_source=comet_headerless_login&next=&encpass=%23PWD_BROWSER%3A5%3A1738437266%3AAX1QABf1pYaBrI3JsfZjdrE0xgj%2F%2BK7BamxCLO5kzfLkWGZGZyvBIv2UyNig4Bs14uz3THFny8RvpBsQHzCsxL%2BgxFfJNC0z%2FTwcWF7CNEsc6aWXjO4RFAaNlQ9%2FhC6kC70%2FuTNqPjk%3D"

 

What you see here is the result of my attempt to log into Facebook.

The auto-generated script mimics every web request needed to repeat what you just did manually in the browser.

While this script probably isn’t ready-to-use, it shows how you can automate advanced web service scenarios with Invoke-WebRequest and Invoke-RestMethod. Let’s take a quick look at what the sample script illustrates:

 

“Post” or “Get”?

In our previous parts, we used simple GET requests: all information was visibly transmitted as part of the URL.

A more sophisticated method is POST which can transfer data (i.e. web service arguments) transparently in the background. The -Method parameter lets you select POST or GET. Facebook uses POST (just like most form-based requests do):


Invoke-WebRequest -UseBasicParsing -Uri "https://www.facebook.com/login..." -Method "POST" 

 

Session State

To maintain session state between consecutive calls to the cmdlets, a “session” variable is used. In the example, the session variable was initialized with some cookies:


$session.Cookies.Add((New-Object System.Net.Cookie("dpr", "3", "/", ".facebook.com")))
Invoke-WebRequest -UseBasicParsing -Uri "https://www.facebook.com/login..." -WebSession $session `
  

 

It can also be empty at first, and will then be populated by the web service during your first call. Use the -SessionVariable parameter to initialize a new variable. Make sure you submit the *name* of the variable only. Do not use a dollar sign to access it.


$result = Invoke-WebRequest -UseBasicParsing -Uri https://www.google.com/ -SessionVariable newSession 

 

Once the first call succeeds, your web session is accessible in the new variable, and you can see that google.com has already planted three cookies in the session:


PS C:\> $newSession

Headers               : {}
Cookies               : System.Net.CookieContainer
UseDefaultCredentials : False
Credentials           : 
Certificates          : 
UserAgent             : Mozilla/5.0 (Windows NT; Windows NT 10.0; de-DE) WindowsPowerShell/5.1.19041.5369
Proxy                 : 
MaximumRedirection    : -1

PS C:\> $newSession.Cookies Capacity Count MaxCookieSize PerDomainCapacity -------- ----- ------------- ----------------- 300 3 4096 20

 

Here is the cookie content:


PS C:\> $newSession.Cookies.GetCookies('https://www.google.com/') | Select-Object -Property Expires, Name, Value

Expires             Name          Value                                                                                                     
-------             ----          -----                                                                                                     
03.03.2026 20:39:06 SOCS          CAAaBgiAyPW8Bg                                                                                            
31.07.2025 21:39:06 AEC           AVcja2cek_VvVSyvKtabbT0XPcBwki0HfvwAHlZbiV49CUzW_zpXQ8gBgck                                               
04.03.2026 12:57:24 __Secure-ENID 25.SE=GTk5Q-nN7tysG4MdAKTtBnk6dOP4KwH2mk8BDAZdmmlI7eUvn3xZ2657kI7u11LBVS9eDt33fQo5tBMx7ax-RK4TCxJbZ-8L6...

 

Use this session variable to identify yourself in subsequent calls if you need to automate multi-step requests:


$result = Invoke-WebRequest -UseBasicParsing -Uri https://www.google.com/ -WebSession $newSession 
 

 

Headers

Headers are invisible pieces of information that are sent to the web service. These could include authentication tokens, referrals, or anything else you like. The example makes use of this through the -Headers parameter which really is just a simple hash table: a list of key-value pairs:


-Headers @{
  "authority"="www.facebook.com"
  "method"="POST"
  "scheme"="https" 
...
   "upgrade-insecure-requests"="1"
}  
 

 

Content Type

You can tell the web service which content you are willing to accept. Occasionally, web services can send information in multiple formats and choose the one based on the content type you request via the -ContentType parameter:


-ContentType "application/x-www-form-urlencoded" 
 

Good2know

Your ultimate PowerShell Cheat Sheet

Unleash the full potential of PowerShell with our handy poster. Whether you're a beginner or a seasoned pro, this cheat sheet is designed to be your go-to resource for the most important and commonly used cmdlets.

The poster is available for download and in paper form.

PowerShell Poster 2023

Get your poster here!

 

 

Related links 

 

Related posts

5 min read

Using .NET Libraries in PowerShell - Best Practice and Quick Start

Most PowerShell cmdlets are simply wrappers around underlying .NET libraries. In this series, we’ll take a closer look...

5 min read

How To Use Web Services in PowerShell - Advanced Options

In the previous parts we looked at the basic tasks Invoke-WebRequest and Invoke-RestMethod perform, and how both...

5 min read

How To Use Web Services in PowerShell - Invoke-RestMethod Deep Dive

In part 2 we looked at Invoke-WebRequest. Today we focus on Invoke-RestMethod: this cmdlet performs the same tasks but...

About the author: