PowerShell Command to Display Specific Text from a Website: file.txt with Get-Content

Abstract: Resolve the error when using Get-Content with URLs by fetching web pages via Invoke-WebRequest and extracting text with regular expressions.

Created: 2026-10-07 by
To display specific text from a website in PowerShell, you must use Invoke-WebRequest or Invoke-RestMethod to fetch the HTML content first. The Get-Content cmdlet only reads local files and cannot process web URLs directly. After retrieving the page, you can filter the resulting HTML string using regular expressions or string manipulation methods to extract the desired information.

Why Get-Content Fails with URLs

A common misconception among beginners is that Get-Content (or its alias cat) can read remote resources like it does local files. This is technically incorrect. Get-Content is designed exclusively for reading file streams from the local filesystem. If you attempt to run Get-Content https://ss64.com/nt/, PowerShell will throw an error because it interprets the URL as a non-existent local path.

To interact with web content, you need cmdlets that handle HTTP protocols. The primary tools for this are Invoke-WebRequest and Invoke-RestMethod. These commands send an HTTP GET request to the specified URL, download the response body (usually HTML), and return it to your PowerShell session for further processing.

Fetching Web Content with Invoke-WebRequest

The most robust way to retrieve raw HTML is using Invoke-WebRequest. This cmdlet returns a complex object containing headers, status codes, and the parsed HTML content. To get the raw text of a webpage, you access the .Content property of the returned object.

$response = Invoke-WebRequest -Uri "https://ss64.com/nt/"
$htmlText = $response.Content

This approach gives you the complete source code of the page. While powerful, working with raw HTML requires careful parsing because web pages contain markup tags, scripts, and styles that are not part of the visible text. For simple text extraction, you may need to strip these tags or search for specific patterns within the larger string.

Alternative: Using Invoke-RestMethod

If you are dealing with structured data like JSON or XML, Invoke-RestMethod is often preferable because it automatically deserializes the response into PowerShell objects. However, for plain HTML text, it behaves similarly to Invoke-WebRequest but may handle certain character encodings differently. It is generally recommended to stick with Invoke-WebRequest when you need full control over the raw HTML stream.

Extracting Specific Text Patterns

Once you have the HTML content stored in a variable, you can use PowerShell's powerful string matching capabilities to find specific text. Regular expressions are the most efficient tool for this task. You can use the -match operator or the [regex]::Matches() method to locate patterns.

For example, if you want to find all links on the SS64 homepage, you might look for anchor tags. A simple regex pattern to find text between <h1> tags could look like this:

$pattern = "<h1>(.*?)</h1>"
$matches = [regex]::Matches($htmlText, $pattern, [System.Text.RegularExpressions.RegexOptions]::Singleline)
foreach ($match in $matches) {
    Write-Output $match.Groups[1].Value
}

This script searches through the entire HTML string, identifies any <h1> elements, and extracts the inner text. The [System.Text.RegularExpressions.RegexOptions]::Singleline option ensures that the dot (.) matches newline characters, which is crucial since HTML tags often span multiple lines.

Simpler String Searches

If regular expressions seem too complex for your needs, you can use basic string methods. The .IndexOf() and .Substring() methods allow you to find a keyword and extract a portion of the string around it. However, this method is fragile and breaks easily if the website structure changes. Regular expressions are more resilient and should be preferred for production scripts.

Handling Encoding Issues

Web pages often use different character encodings such as UTF-8, ISO-8859-1, or Windows-1252. When you retrieve HTML via Invoke-WebRequest, PowerShell attempts to detect the encoding based on the HTTP headers or meta tags in the HTML. If the detection fails, you might see garbled characters (mojibake) in your output.

To ensure correct display, you can explicitly specify the encoding when making the request or convert the content after retrieval. Most modern websites use UTF-8, which PowerShell handles well by default. If you encounter encoding issues, check the .Headers collection of the response object to see what charset was declared.

For more advanced automation tasks involving interactive prompts, consider exploring how to enhance your workflow with external tools. See Automating PowerShell Prompt using Control Sequences with fzf for tips on improving command-line usability.

Best Practices for Web Scraping

When scraping websites, always respect the site's terms of service and robots.txt file. Avoid sending too many requests in a short period, as this can be considered a denial-of-service attack. Use appropriate delays between requests if you are processing multiple pages.

Additionally, store your results in structured formats like CSV or JSON rather than just printing them to the console. This makes it easier to analyze the data later. You can export your findings using Export-Csv or ConvertTo-Json.

If you are managing large-scale deployments where monitoring connected machines is essential, understanding how to automate device interactions is key. Read Monitoring Connected Machines to learn about broader automation strategies.

Frequently Asked Questions

Can I use curl.exe instead of Invoke-WebRequest?

Yes, you can call curl.exe or Invoke-WebRequest's alias curl to fetch content. However, native PowerShell cmdlets provide better integration with the pipeline and object-oriented data structures, making filtering easier than parsing raw CLI output.

How do I handle dynamic JavaScript-rendered content?

Invoke-WebRequest only retrieves the static HTML source. It does not execute JavaScript. For dynamic content, you need a headless browser solution like Selenium or Playwright, which can interact with the page as a real user would.

What if the website blocks my PowerShell script?

Websites may block requests that lack a proper User-Agent header. You can mimic a browser by adding headers to your request: -Headers @{ 'User-Agent' = 'Mozilla/5.0' }. This often bypasses simple bot protection mechanisms.

Is there a limit to how much text I can retrieve?

There is no hard limit on the size of the content you can retrieve, but very large responses may consume significant memory. For massive files, consider streaming approaches or downloading to a temporary file first before processing.

How do I save the retrieved HTML to a local file?

You can pipe the content to Set-Content or Out-File. For example: $response.Content | Set-Content -Path "./page.html". This allows you to inspect the HTML offline or debug parsing issues without repeatedly hitting the server.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More