Text Files (PowerShell)

Here’s some examples of how you can work with Text Files in Windows PowerShell

Open Text File – using the Get-Content cmdlet (alias is “gc”).

Get-Content “C:terms.txt”

Write to Text File – using the Out-File cmdlet (WARNING: This will save the file but overwrite any existing file)

out-file “C:folderterms.txt”

Append to an existing Text File. It will create the file if it doesn’t already exist.

out-file “C:folderterms.txt” –append

This will save the file but will not overwrite any existing file

out-file “C:folderterms.txt” -noclobber

Search within Text File (this example will search for the word “Date” in a text file using –match. This returns the matched line of text if the $variable is an array, however will return “True” or “False” if $variable is an object)

$text = Get-Content “C:terms.txt”
$text -match “Date”

Returns: System.Array

Search for the word “Date” and/or the words “Pay” and “Change” in a text file

$text = Get-Content “C:terms.txt”
$text -match “Date|Pay|Change”

Get the last 10 lines from a Text File

(gc “C:terms.txt”)[-10..-1]

Get the 10th last line only from Text File

(gc “C:terms.txt”)[-10]

Replace Text within Text File – using -replace

$text = Get-Content “C:terms.txt”
$text -replace “Five”, “Twenty”

Replace the text for the 5th Element in an Array

$text -replace $text[4], “Twenty”

Replace the text for the last Element in an Array

$text -replace $text[-1], “Twenty”




No comments yet.

Leave a Reply