Invoke-WebRequest is a tool that many in IT shy away from. It is essentially curl
for Windows, which you can use as an alias if you’d like. I have worked with a small number of APIs, and I am passingly familiar with web protocols on my side of the fence. Since I work in automation, my world generally consists of things like event triggers, scheduled tasks, and executables, and API management is generally done through webhooks with app integrations. I have really mostly used Invoke-WebRequest to download files when I couldn’t use Start-BITSTransfer
, but there are a broad range of things you’re able to do.
$uri = "https://www.wizardshell.com"
$Response = Invoke-WebRequest -URI $uri # By default this is a 'GET' request
Now the webpage is stored in a variable. It’s not as clean as our usual objects, but let’s see how we can manipulate it.
$response.StatusCode
$response.Headers
$response.Links.href
Invoke-WebRequest Practical Examples
Microsoft’s webpage has an example where you can grab an answer off of Bing. This doesn’t work for all content, just that info Bing will enter in a container.
$Response = Invoke-WebRequest -URI https://www.bing.com/search?q=how+many+feet+in+a+mile
$Response.InputFields | Where-Object {
$_.name -like "* Value*"
} | Select-Object Name, Value
This command can be used to trigger web APIs or submit online forms. This can be a massive force multiplier in IT, regardless of whether you’re calling an on-prem application, Windows API, or a Cloud resource. For example, I’ve seen PowerShell used with Sophos API to locate specific computers, or HRIS to automate user provisioning.
# Sign up for my robocalls!
$Uri = 'https://api.wizardshell.com/v2/profile'
$Form = @{
firstName = 'John'
lastName = 'Doe'
email = 'john.doe@domain.com'
avatar = Get-Item -Path 'C:\Pictures\me-sfw.png'
birthday = '1997-2-14'
mobile = '123-456-7890'
}
$Result = Invoke-WebRequest -Uri $Uri -Method Post -Form $Form # 'POST' request
# Sometimes, you'll want to submit hash tables that include hash tables. If this fails to parse, the ConvertTo-JSON cmdlet is needed.
There are also a lot of public facing endpoints that you can interact with. I’m sure you could find a web site that would let you pull the weather using Invoke-WebRequest.
For instance, if you want to know your public IP, you can type this:
(Invoke-WebRequest -uri "http://ifconfig.me/ip").Content
This is the tip of a colossal iceberg. There is a massive amount of potential here, including credential passing, web crawling, session management, proxy users. I’m sure if you are able to generate an API token you could perform all actions in your ticketing system from the terminal.