Read a File and Format Line in Powershell

With automation, reading data from a text file is a mutual scenario. Most programming languages have at least one way of reading text files, and PowerShell is no exception. The PowerShell Get-Content cmdlet, a PowerShell tail equivalent, reads a text file's contents and imports the data into a PowerShell session.

The PowerShell Become-Content cmdlet is an indispensable tool when you lot need to apply text files as input for your script. Maybe your PowerShell script needs to read a computer list to monitor or import an email template to ship to your users. PowerShell Get-Content easily supports these scenarios!

How almost following a log file in real-fourth dimension? Yes, the PowerShell Get-Content can do that, also!. Continue reading this article, and you will larn how to use the Get-Content cmdlet to read text files in PowerShell.

Prerequisites

If you're interested in following the examples in this tutorial, yous volition need the following requirements.

  • You'll need a computer that is running on Windows 10. This tutorial uses Windows ten version 20H2. But don't worry, you'll exist okay with the Windows 10 version that you have.
  • You should take at least Windows PowerShell 5.i, or PowerShell 7.1 installed on your computer. Hither PowerShell 7.one is used, but either will version will piece of work!
  • Y'all'll be writing and testing commands, so you lot'll need a code editor. The recommended editors are Windows PowerShell ISE, built-in to Windows, and Visual Studio Code (VSCode). This commodity uses VSCode.
  • It will also help if you create a working directory on your figurer. The working folder can be anywhere you want. However, you'll notice that the examples in this tutorial reside in the C:\demo folder.
  • To get started, you lot need some content! Create a file, in your working directory, with the name fruits.txt that includes x different fruits for simplicity. You volition exist using this text file in all the examples.
            cherry-red  berry  apricot  papaya  raspberry  melon  peach  tangerine  cantaloupe  orange          

Don't know which PowerShell version yous have? Visit the article How to Cheque your PowerShell Version (All the Means!).

Reading a Text File and Returning the Result as a String Array

The Get-Content cmdlet reads content from a file, and by default, returns each line of a text file as a string object. As a consequence, the collection of PowerShell objects becomes an array of string objects.

The below lawmaking reads the contents of the fruits.txt file and displays the result on the PowerShell panel every bit seen in the beneath screenshot.

Retrieving the text file content using PowerShell Get-Content.
Retrieving the text file content using PowerShell Get-Content.

Get-Content reads and stores the content every bit an array, but how exercise you know that for sure? First, save the content to a PowerShell object which you can and so examine to determine the type.

            Salve the content into to a object  $fruits = Get-Content .\fruits.txt  Display the blazon of the object  $fruits.GetType()  Retrieve the count of items within the object  $fruits.Count  Output the contents of the object to the panel  $fruits          

Looking at the screenshot beneath, the $fruits variable is an array that contains ten objects. Each object represents a unmarried line of text.

Confirming that the text file content is stored as an array.
Confirming that the text file content is stored as an array.

Returning a Specific Line From a Text File

In the previous case, you've learned that the default Get-Content result is an assortment or a collection of objects. Each particular in a collection corresponds to an index number, and PowerShell indexes typically outset at zippo.

The screenshot below shows that there are ten items in the cord array. The assortment indexed the ten items from zero to nine.

Showing that the indexed items in the string array start at zero index.
Showing that the indexed items in the cord array start at zero index.

To merely display the fifth line of content, you'll need to specify the index number iv, enclosed in foursquare brackets (known every bit assortment notation).

            (Go-Content .\fruits.txt)[4]                      

You may notice that the Get-Content command is enclosed in a parenthesis. This notation tells PowerShell to run the command enclosed in the parenthesis starting time earlier other operations.

In the screenshot below, you lot'll run into that the just returned result is raspberry, which is the item at index 4 and corresponds to the fifth line in the text file.

Returning a specific line from Get-Content results.
Returning a specific line from Get-Content results.

What if you need to get the content in the last line? Thankfully, yous exercise not need to know the total number of lines. Instead, use [-1] every bit the index, and Get-Content will display only the concluding line of the file.

            (Become-Content .\fruits.txt)[-1]                      

Limiting the Number of Superlative Results Returned by Get-Content

Utilise the TotalCount parameter of Get-Content to retrieve a specified number of lines from a text file. The TotalCount parameter accepts a long value which means a maximum value of 9,223,372,036,854,775,807.

For example, the command below reads the content and limits the result to 3 items.

            Become-Content .\fruits.txt -TotalCount three                      

As you would await, the result below displays just the height iii lines from the beginning of the text file.

Reading the top three results using the Get-Content command and the TotalCount parameter.
Reading the tiptop 3 results using the Get-Content control and the TotalCount parameter.

Use the PowerShell Tail Parameter to Return Results From the End of a File

In the previous example, you used the PowerShell Get-Content cmdlet to read a text file and limit the top results. Information technology is also possible to attain the opposite with PowerShell Go-Content. Use the PowerShell Tail parameter to read a specified number of lines from the end of a file.

The instance code below reads the text file and displays the content of the bottom four lines.

            Go-Content .\fruits.txt -Tail 4                      

Later running the PowerShell tail command, the expected upshot will be limited to the last 4 lines of content, as shown in the image beneath.

Getting the results from the end of a file using the Get-Content Tail parameter.
Getting the results from the end of a file using the Go-Content Tail parameter.

The Tail parameter is often used together with the Wait parameter. Using the Wait parameter keeps the file open and checks for new content once every 2d. The demonstration beneath shows the Tail and Wait parameters in action. To exit Wait, use the primal combination of CTRL+C.

            Get-Content -Path .\fruits.txt -Tail 1 -Expect                      
Using the wait and Tail parameters with Get-Content.
Using the wait and Tail parameters with Get-Content.

Returning the Results equally a Single Cord

You lot may have noticed in previous examples that yous've been dealing with string arrays every bit the PowerShell Get-Content output. And as you've learned so far, the nature of arrays allows you to operate on the content ane detail at a time.

Arrays oft work cracking only tin brand replacing strings more hard. The Raw parameter of Go-Content reads a file's entire content into a unmarried string object. Although the code below is the aforementioned as used within the first instance, the Raw parameter stores the file content equally a single string.

            Save the content into to a object  $fruits = Get-Content .\fruits.txt -Raw  Display the type of the object  $fruits.GetType()  Retrieve the count of items within the object  $fruits.Count  Output the contents of the object to the console  $fruits          

The screenshot below demonstrates that adding the Raw parameter to Become-Content results in treating the content every bit a single string and not an assortment of objects.

Confirming that the Raw parameter of Get-Content reads the file content as a single string object.
Confirming that the Raw parameter of Go-Content reads the file content as a single string object.

Once you take the contents of a file in a single string using the Raw parameter, what tin can you do with it? Perhaps you need to find and supervene upon a cord inside of that file's content. In the example below, Get-Content reads the content of a file as a unmarried string. And so, using the supervene upon operator, replace a specific word with another.

Related: Finding and Replacing Strings

            # Get the raw content of the text file $fruits = Get-Content .\fruits.txt -Raw # Display the content $fruits # Find and supplant the discussion 'apricot' with 'mango' $fruits -supervene upon 'apricot','mango'                      
Reading the content of a text file as a single string and replacing a word using the replace operator.
Reading the content of a text file as a single string and replacing a word using the replace operator.

Read Content Only from Files that Matched a Filter

Practise you have a folder full of files merely demand to read the content of a select few? With PowerShell Get-Content, you practice non take to filter the files separately before reading the files' contents. The Filter parameter of Get-Content limits which files the cmdlet reads.

To demonstrate reading the content of only select files, first, create a couple of files to read. As shown below, create the files in your working folder using Add-Content.

            # Add together-Content creates the log1.log and log2.log file if they don't be already and adds the given value Add-Content -Value "This is the content in Log1.log" -Path C:\demo\Log1.log Add-Content -Value "This is the content in Log2.log" -Path C:\demo\Log2.log # Verify that the files have been created Get-ChildItem C:\demo                      
Creating test .log files using Add-Content.
Creating test .log files using Add together-Content.

With your test files created, use the Filter and Path parameters to only read .log files in the root directory. The asterisk used in the filter definition indicates to Get-Content to read any file ending with .log. The ending asterisk of the path parameter limits the reading of files to just the root directory.

            Go-Content -Path C:\demo* -Filter *.log          

Every bit shown in the beneath output, simply the content from the .log files is displayed.

Using the Filter parameter with PowerShell Get-Content to limit the read files.
Using the Filter parameter with PowerShell Get-Content to limit the read files.

Related: Get-ChildItem: Listing Files, Registry, Certificates, and More than equally One

Reading the Alternate Data Stream of a File

Until now, y'all have been working exclusively with text files, but Go-Content can read data from the alternate data stream (ADS) of a file. Feel free to read more than almost streams, but y'all tin can remember of a stream every bit another information attribute stored alongside the typical file contents.

Alternate data streams are a feature of the Windows NTFS file system, therefore this does not apply to Get-Content when used with non-Windows operating systems.

Y'all tin see alternate data streams by running Go-Item with the Stream parameter. When referencing a file using the Stream parameter, Get-Item returns a property chosen Stream as shown below. This default file content stream is represented with :$Information.

To demonstrate the default :$DATA stream, employ the Get-Particular cmdlet to brandish all available streams in the file fruits.txt. As shown below, Get-Item displays a unmarried stream.

            Get-Item -Path .\fruits.txt -Stream *                      
Listing all available streams in a file using Get-Item.
Listing all available streams in a file using Get-Particular.

The Stream parameter of Get-Content explicitly reads the content of the default :$Data stream equally shown below. The returned content is the same as the default Get-Content output every bit the :$Information stream is read by default.

            Get-Content -Path .\fruits.txt -Stream ':$DATA'                      
Explicitly reading the :$DATA stream using Get-Content.
Explicitly reading the :$Data stream using Get-Content.

To demonstrate retrieving an alternating data stream using Become-Content, modify a file using Add-Content to add together the new stream. Utilise Become-Item to show the new stream alongside the default :$Data stream, as seen in the beneath example.

            # Add together a new ADS named Cloak-and-dagger to the fruits.txt file Add-Content -Path .\fruits.txt -Stream Secret -Value 'This is a underground. No one should find this.' Get-Detail -Path .\fruits.txt -Stream *                      
Adding the Secret alternate data stream using Add-Content and displaying the new stream with Get-Item.
Calculation the Undercover alternate data stream using Add together-Content and displaying the new stream with Become-Item.

As simply the :$DATA stream is read past default, use the Stream parameter of Get-Content to think the new Hole-and-corner stream content. As shown below, the Surreptitious stream content is displayed instead of the default file content.

            Get-Content -Path .\fruits.txt -Stream secret                      
Using Get-Content to read the Secret alternate data stream content.
Using Get-Content to read the Secret alternate data stream content.

Next Steps With PowerShell Get-Content

In this article, you've learned many ways to use Get-Content to read and manipulate content. You've even learned that Get-Content is flexible enough to read content from alternate data streams!

With what you've learned in this commodity, what other ways tin can you use Get-Content in your piece of work? Maybe y'all tin use Become-Content to make up one's mind if a fill-in file is outdated and trigger an automatic call to run a fill-in job?

ridgewaytherstund.blogspot.com

Source: https://adamtheautomator.com/powershell-get-content/

0 Response to "Read a File and Format Line in Powershell"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel