Powershell – Reading Text File


Reading text file

Get-Content
To quickly read and display a text file content, type:

Get-Content c:\scripts\test.txt

To obtain some stats of file content, type:

Get-Content c:\scripts\test.txt | Measure-Object

To retrieve the last 5 lines, type:

Get-Content c:\scripts\test.txt | Select-Object –last 5

To retrieve first five lines but using a Get-Content property, type:

Get-Content c:\scripts\test.txt –totalcount 5

To tail the end of a file in real time, type:

Get-Content c:\scripts\test.txt –Wait

To filter a text file and see only lines that match a string, type:

Get-Content c:\scripts\test.txt –Wait | Where-Object {$_ -match “ERROR”}

Using the text file content to use it with another cmdlet, like:

Get-Content c:\scripts\test.txt | Foreach-Object {Get-Wmiobject -computername $_ win32_bios}

Note: Get-Content alias is gc, type or cat
Set-Content
To copy first 50 lines to a new text file, type:

Get-Content c:\scripts\test.txt –totalcount 50 | Set-Content c:\scripts\test_copy.txt

 

In Depth
http://technet.microsoft.com/en-us/library/ee176843.aspx

Tested With
PowerShell 4.0

Advertisements
Categories: Powershell | Leave a comment

Post navigation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: