PowerShell is a powerful command-line shell and scripting language that allows administrators to automate tasks on Windows systems. With PowerShell, you can create, edit, and manage text files programmatically without needing to use a text editor.
In this comprehensive guide, we will cover everything you need to know to work with text files in PowerShell, including:
- Creating new text files
- Writing and appending text
- Replacing text
- Using the nano text editor
- Handling file encodings
- Importing/exporting text
- Searching and manipulating file contents
Whether you‘re an IT pro automating management tasks or a developer building scripts, this guide has what you need to master text files in PowerShell. Let‘s get started!
Creating Text Files
To create a new empty text file in PowerShell, use the New-Item cmdlet.
For example, to create a file called myfile.txt in the current folder, run:
New-Item myfile.txt
You can also specify a full file path to create the text file in another location:
New-Item C:\Users\John\Documents\myfile.txt
When creating new text files, PowerShell does not add a Byte Order Mark (BOM) or encoding signature by default. The file will use UTF-8 encoding unless you specify otherwise.
Specifying the File Encoding
You can explicitly define the encoding when creating a text file using the -Encoding parameter:
New-Item myfile.txt -Encoding ASCII
Common encodings you may use include:
- ASCII: Plain English text without special characters
- UTF8: Supports wide range of Unicode characters
- UTF32: Fixed-width Unicode encoding
- Unicode: UTF-16 encoding
Choosing the correct encoding is important if you will be writing special characters or text in different languages.
Writing Text to Files
To write text content into a new file or append text to an existing file, use the Set-Content and Add-Content cmdlets.
Replacing File Contents
Set-Content will completely replace all text in a file with the content you provide. For example:
Set-Content myfile.txt "This is new text content!"
This clears myfile.txt first before writing the string.
Appending File Contents
To append text and keep existing data, use Add-Content instead:
Add-Content myfile.txt "Appended text line"
Now myfile.txt will have both the original text and our new appended line.
Both cmdlets support writing strings directly or reading content from another file:
Get-Content data.txt | Add-Content myfile.txt
This appends the contents of data.txt into myfile.txt. Pretty handy!
Using the Nano Text Editor
While you can write PowerShell scripts to modify files programmatically, you may also want to quickly edit files manually.
PowerShell does not come with a built-in text editing command, but we can easily install the popular Nano editor!
First, run the Chocolatey package manager script as admin to prepare PowerShell:
Set-ExecutionPolicy Bypass -Scope Process -Force; Invoke-Expression ((New-Object System.Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1‘))
Now install Nano:
choco install nano
Once installed, you can launch Nano by specifying any text file to open and edit:
nano myfile.txt
This will launch the Nano console editor where you can edit the text contents, save changes, search text, and more.
Here are some handy Nano keyboard shortcuts:
- Ctrl + X – Exit editor
- Ctrl + O – Save changes
- Ctrl + G – Get help
- Ctrl + W – Search for text
Feel free to enhance PowerShell further with command editors like PSReadLine as well!
Handling File Encodings with Import/Export
When exchanging text files with other systems, you may need to expressly define file encodings.
The Export-Csv and Import-Csv cmdlets include encoding parameters for this scenario.
For example, to export data to a UTF-16 LE encoded file:
$data | Export-Csv utf16file.csv -Encoding utf16LE
To later import back as UTF8 encoded text:
$textdata = Import-Csv utf16file.csv -Encoding utf8
This provides full control over text encoding conversions.
Replacing Text Using Regular Expressions
To do find-and-replace text operations in PowerShell, use regular expressions with the -replace operator.
For example, this replaces email addresses with REDACTED in myfile.txt:
(Get-Content myfile.txt) -replace ‘[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+‘, ‘REDACTED‘ | Set-Content myfile.txt
Let‘s break this down:
(Get-Content myfile.txt)– Gets text contents-replace– Operator to find/replace text- ‘[regex pattern]‘ – Matches email pattern
‘REDACTED‘– Replacement text| Set-Content myfile.txt– Writes changes back
The regular expression makes this a very flexible find-and-replace tool!
Searching Text Files
You can search for patterns and extract matching text from files using PowerShell‘s comparison operators.
For example, find lines containing ‘Hello‘ in myfile.txt:
Select-String ‘Hello‘ myfile.txt
Expand this to return the matched line:
Get-Content myfile.txt | Select-String ‘Hello‘ | ForEach { $_.Line }
Here we grab the line property from the MatchInfo result object.
You can further search conditionally based on regular expression matches:
Get-Content myfile.txt | Where { $_ -match ‘[0-9]+\.[0-9]+‘ }
This returns lines containing a number pattern like ‘3.145‘. Very handy for parsing logs and reports!
Importing/Exporting CSV and JSON Text
Text files like CSV, TSV and JSON documents can be easily handled with built-in PowerShell converters:
- Import CSV documents using
Import-Csv - Export objects to text with
Export-Csv
For example:
# Hash table to export
$data = @{
Name = ‘John‘
Age = 25
}
# Export data to CSV format
$data | Export-Csv -Path output.csv
# Import back from CSV
$csvData = Import-Csv -Path output.csv
You have similar ConvertTo-Json and ConvertFrom-Json cmdlets to handle JSON text data which is useful for web APIs.
These tools really help when working with semi-structured data!
Summary
This guide covered key skills like creating, reading, editing, searching and encoding text documents in PowerShell.
Whether it‘s basic system administration tasks or manipulating data for scripts, you can now handle text files like a pro!
Some final tips:
- Use aliases like
catinstead ofGet-Contentto save typing - Look into *-Content cmdlets like
Get-Content,Set-Content,Add-Content - Import/Export text data as needed for commands expecting objects
- Utilize Nano as a quick text file editor from within PowerShell
- Leverage regular expressions to powerfully find, match and replace text
With a bit of PowerShell practice, text files will become second nature. The flexibility helps solve many automation and reporting challenges.
Hopefully this guide paves the way to mastering text files in your PowerShell journey! Let me know in the comments if you have any other text file tips.


