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.
Sometimes configuration files or scripts include identifiers that need to be updated automatically — for example, replacing a generic keyword like "rule-template" with a dynamic name based on a service or environment.
This Snipp shows how to:
Replace this:
rule-template
With something like:
rule-example-service
Where "example.service" is the dynamic input.
# Define the original dynamic name
$name = "example.service"
# Normalize the name (e.g., replace '.' with '-')
$normalizedName = $name -replace '\.', '-'
# Read the text file content
$content = Get-Content -Path "file.txt" -Raw
# Replace the exact identifier
$content = $content -replace 'rule-template', "rule-$normalizedName"
# Save the updated content
Set-Content -Path "file.txt" -Value $content
This ensures that:
"rule-template" are replacedThis method is useful when working with reusable config files across different services or environments. PowerShell makes it easy to normalize and apply names consistently, reducing manual edits and potential mistakes.
To display JSON in a structured and readable format directly in PowerShell, you can pipe a JSON string through ConvertFrom-Json and then ConvertTo-Json with an appropriate -Depth parameter. This allows you to avoid using intermediary variables and outputs neatly formatted JSON directly to the console.
'{"name":"John","age":30,"address":{"street":"123 Main St","city":"Anytown"},"phones":["123-4567","987-6543"]}'
| ConvertFrom-Json
| ConvertTo-Json -Depth 10
ConvertFrom-Json parses the raw JSON string into a PowerShell object.ConvertTo-Json re-serializes the object with proper indentation.-Depth parameter ensures that nested objects are fully expanded in the output.This approach is useful for quickly inspecting JSON structures without needing temporary variables or additional tools.
The msDS-UserPasswordExpiryTimeComputed attribute in Active Directory stores the user’s password expiration time as a large integer in Windows FileTime format. This format counts 100-nanosecond intervals from January 1, 1601 (UTC). To get a readable date and time, you must convert this number to a standard datetime format using the appropriate method for your platform.
How to Convert:
FromFileTimeUtc in PowerShell or .NET.Example in PowerShell:
[DateTime]::FromFileTimeUtc($filetimeValue)
Handling the Special “Magic” Number:
If the value equals 9223372036854775807 (the maximum 64-bit integer), it is a special indicator that the password never expires. This number is not a real timestamp and should not be converted to a date. Instead, treat it as a flag meaning “no expiration.”
Summary:
9223372036854775807 as a sentinel meaning “password never expires.” Avoid converting this sentinel to a datetime.This solution demonstrates how to retrieve the password expiration date of a user account in Active Directory using PowerShell. It uses the Get-ADUser cmdlet from the Active Directory module and queries the msDS-UserPasswordExpiryTimeComputed property, which holds the computed expiration date in FILETIME format.
If querying by -Identity returns an error such as "Cannot find an object with identity," switching to a -Filter approach with the SamAccountName is recommended. Also, ensure that the Active Directory module is imported, the domain context is correct, and the executing user has appropriate permissions.
# Import the Active Directory module if not already loaded
Import-Module ActiveDirectory
# Replace 'username' with the actual SamAccountName of the user
$user = Get-ADUser -Filter {SamAccountName -eq "username"} -Properties msDS-UserPasswordExpiryTimeComputed
# Convert the FILETIME to a readable DateTime object
$passwordExpiry = if ($user."msDS-UserPasswordExpiryTimeComputed") {
[datetime]::FromFileTime($user."msDS-UserPasswordExpiryTimeComputed")
} else {
"Password does not expire or no expiration set."
}
# Output the result
[PSCustomObject]@{
UserName = $user.SamAccountName
PasswordExpiry = $passwordExpiry
}
Key Points:
-Filter with SamAccountName to avoid identity resolution issues.msDS-UserPasswordExpiryTimeComputed returns the expiration time as FILETIME.To see all the services on your system, use the Get-Service cmdlet:
Get-Service
This outputs a list showing:
This command helps you get an overview of all services and their current state.
PowerShell is a powerful tool for managing system services, offering flexibility and control through straightforward commands. This guide covers the essentials of listing, searching, and managing services.
You often need administrative privileges to manage services. Running PowerShell as an administrator ensures you have the necessary permissions to start, stop, or modify services.
In PowerShell, you can show elapsed time using a simple timer script. Start by capturing the current time when your script begins with $StartTime = $(Get-Date). Then, calculate the elapsed time by subtracting the start time from the current time: $elapsedTime = $(Get-Date) - $StartTime. Format the elapsed time into hours, minutes, and seconds using the "{0:HH:mm:ss}" format and apply it to a DateTime object: $totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks).
$StartTime = $(Get-Date)
# Your script here
$elapsedTime = $(Get-Date) - $StartTime
$totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
Write-Host "Total elapsed time: $totalTime"
For more details and discussions, you can refer to this Stack Overflow post.
The Invoke-WebRequest PowerShell cmdlet is used to fetch content from a web page on the internet. It allows you to make HTTP requests, retrieve HTML content, and interact with web APIs directly from your PowerShell script.
Gets content from a web page on the internet.
# Here we are asking Google about PowerShell and saving the response
$Response = Invoke-WebRequest -URI https://www.google.com/search?q=powershell
# We use the Content property of $Response to access the webpage content
$Response.Content
In the example above, $Response will store the content retrieved from the specified URL (https://www.google.com/search?q=powershell). You can then use $Response to parse and extract information from the web page as needed.
To learn more about Invoke-WebRequest, you can visit the Microsoft documentation page. This resource provides detailed information and examples to help you understand and use this cmdlet effectively.