Accessing URLs and APIs with PowerShell
Retrieving data from a URL or calling a web API is one of the most common PowerShell tasks. Whether you want to check a website’s status, download a file, or interact with a REST API, PowerShell provides built-in commands for this purpose.
1. Using Invoke-WebRequest
Invoke-WebRequest is used to fetch web pages or files.
Example:
$response = Invoke-WebRequest -Uri "https://example.com"
$response.Content
This command returns the full HTTP response, including status code, headers, and body content.
To download a file:
Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "C:\Temp\file.zip"
2. Calling APIs with Invoke-RestMethod
For APIs that return JSON or XML, Invoke-RestMethod is the better choice. It automatically converts the response into PowerShell objects:
$data = Invoke-RestMethod -Uri "https://api.github.com"
$data.current_user_url
You can also send POST requests:
Invoke-RestMethod -Uri "https://api.example.com/data" -Method POST -Body '{"name":"John"}' -ContentType "application/json"
3. Running PowerShell from the Command Line
PowerShell commands can be executed directly from the traditional Windows Command Prompt:
powershell -Command "Invoke-WebRequest -Uri 'https://example.com'"
Or, if available, using curl:
curl https://example.com
Summary
With just a few commands, PowerShell becomes a versatile tool for web requests and API communication — ideal for automation, system monitoring, or accessing online data sources.
Comments