Lompat ke konten Lompat ke sidebar Lompat ke footer

Read First 20 Characters of File in Powershell

With automation, reading data from a text file is a common scenario. Almost programming languages take at least one manner of reading text files, and PowerShell is no exception. The PowerShell Get-Content cmdlet, a PowerShell tail equivalent, reads a text file'due south contents and imports the data into a PowerShell session.

The PowerShell Get-Content cmdlet is an indispensable tool when you demand to employ text files equally input for your script. Perhaps your PowerShell script needs to read a computer list to monitor or import an email template to send to your users. PowerShell Get-Content hands supports these scenarios!

How nearly following a log file in real-time? Yes, the PowerShell Get-Content can practise that, too!. Continue reading this article, and you volition learn how to use the Get-Content cmdlet to read text files in PowerShell.

Prerequisites

If you're interested in post-obit the examples in this tutorial, you lot will need the following requirements.

  • You'll need a computer that is running on Windows 10. This tutorial uses Windows x version 20H2. But don't worry, you'll be okay with the Windows 10 version that you accept.
  • You should take at least Windows PowerShell 5.1, or PowerShell 7.1 installed on your calculator. Here PowerShell vii.1 is used, simply either will version volition work!
  • You'll be writing and testing commands, so you'll need a lawmaking editor. The recommended editors are Windows PowerShell ISE, built-in to Windows, and Visual Studio Code (VSCode). This article uses VSCode.
  • It will also help if you create a working directory on your computer. The working folder can be anywhere you desire. However, you'll detect that the examples in this tutorial reside in the C:\demo folder.
  • To become started, y'all demand some content! Create a file, in your working directory, with the name fruits.txt that includes 10 unlike fruits for simplicity. You will be using this text file in all the examples.
            cherry  berry  apricot  papaya  raspberry  melon  peach  tangerine  cantaloupe  orange          

Don't know which PowerShell version you have? Visit the article How to Check your PowerShell Version (All the Ways!).

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

The Get-Content cmdlet reads content from a file, and by default, returns each line of a text file equally a string object. Equally a result, the collection of PowerShell objects becomes an assortment of string objects.

The beneath code reads the contents of the fruits.txt file and displays the result on the PowerShell console as seen in the below 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 equally an array, just how practise y'all know that for sure? First, save the content to a PowerShell object which y'all tin can then examine to make up one's mind the type.

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

Looking at the screenshot below, the $fruits variable is an array that contains x objects. Each object represents a single 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 example, y'all've learned that the default Go-Content upshot is an assortment or a collection of objects. Each item in a drove corresponds to an index number, and PowerShell indexes typically outset at zero.

The screenshot beneath shows that there are ten items in the string array. The array indexed the x items from nil to nine.

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

To only brandish the fifth line of content, y'all'll need to specify the index number 4, enclosed in square brackets (known equally array notation).

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

You may detect that the Get-Content command is enclosed in a parenthesis. This note tells PowerShell to run the command enclosed in the parenthesis first before other operations.

In the screenshot below, you'll see that the simply returned effect is raspberry, which is the detail 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 y'all need to get the content in the final line? Thankfully, you do not need to know the total number of lines. Instead, employ [-1] as the alphabetize, and Get-Content will display merely the concluding line of the file.

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

Limiting the Number of Summit Results Returned by Get-Content

Use 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 ways a maximum value of nine,223,372,036,854,775,807.

For case, the control beneath reads the content and limits the issue to three items.

            Go-Content .\fruits.txt -TotalCount 3                      

As you would expect, the result below displays only the height 3 lines from the showtime of the text file.

Reading the top three results using the Get-Content command and the TotalCount parameter.
Reading the summit iii results using the Get-Content command and the TotalCount parameter.

Utilise 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. It is also possible to accomplish the contrary with PowerShell Get-Content. Use the PowerShell Tail parameter to read a specified number of lines from the end of a file.

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

            Go-Content .\fruits.txt -Tail 4                      

Afterward running the PowerShell tail control, the expected outcome volition exist express to the last four lines of content, equally shown in the paradigm below.

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

The Tail parameter is oft used together with the Expect parameter. Using the Expect parameter keeps the file open up and checks for new content once every 2d. The demonstration below shows the Tail and Wait parameters in action. To go out Wait, utilize the fundamental combination of CTRL+C.

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

Returning the Results as a Single String

You may have noticed in previous examples that you've been dealing with cord arrays as the PowerShell Get-Content output. And equally you've learned and so far, the nature of arrays allows y'all to operate on the content one item at a time.

Arrays often piece of work great but can make replacing strings more hard. The Raw parameter of Get-Content reads a file's entire content into a single string object. Although the lawmaking beneath is the same every bit used inside the first example, the Raw parameter stores the file content every bit a unmarried string.

            Relieve the content into to a object  $fruits = Get-Content .\fruits.txt -Raw  Brandish 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 panel  $fruits          

The screenshot below demonstrates that calculation the Raw parameter to Get-Content results in treating the content as a unmarried string and not an array 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 Get-Content reads the file content as a single string object.

Once you lot have the contents of a file in a unmarried string using the Raw parameter, what tin can you lot do with it? Perhaps y'all demand to observe and replace a cord inside of that file's content. In the example beneath, Get-Content reads the content of a file as a single string. Then, 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 # Detect and supercede the give-and-take 'apricot' with 'mango' $fruits -supercede '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 every bit a unmarried cord and replacing a word using the supervene upon operator.

Read Content Simply from Files that Matched a Filter

Practise you have a folder full of files only need to read the content of a select few? With PowerShell Get-Content, you practise not have 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, get-go, create a couple of files to read. Equally shown beneath, create the files in your working folder using Add-Content.

            # Add-Content creates the log1.log and log2.log file if they don't exist already and adds the given value Add together-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 accept been created Become-ChildItem C:\demo                      
Creating test .log files using Add-Content.
Creating test .log files using Add-Content.

With your examination files created, utilise 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 catastrophe asterisk of the path parameter limits the reading of files to merely the root directory.

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

Equally shown in the below output, only 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: Go-ChildItem: List Files, Registry, Certificates, and More as Ane

Reading the Alternate Data Stream of a File

Until now, y'all take been working exclusively with text files, but Get-Content tin read data from the alternate data stream (ADS) of a file. Feel gratis to read more nearly streams, only you tin think of a stream as another information attribute stored alongside the typical file contents.

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

Yous tin see alternate data streams past running Get-Particular with the Stream parameter. When referencing a file using the Stream parameter, Get-Detail returns a property called Stream as shown below. This default file content stream is represented with :$Data.

To demonstrate the default :$Data stream, apply the Go-Item cmdlet to display all available streams in the file fruits.txt. Equally shown below, Go-Particular 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 Go-Item.

The Stream parameter of Get-Content explicitly reads the content of the default :$DATA stream as shown beneath. The returned content is the same as the default Go-Content output as the :$DATA stream is read by default.

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

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

            # Add a new ADS named Secret to the fruits.txt file Add-Content -Path .\fruits.txt -Stream Secret -Value 'This is a secret. No 1 should observe this.' Get-Particular -Path .\fruits.txt -Stream *                      
Adding the Secret alternate data stream using Add-Content and displaying the new stream with Get-Item.
Adding the Cloak-and-dagger alternate data stream using Add-Content and displaying the new stream with Get-Detail.

As only the :$Information stream is read by default, use the Stream parameter of Become-Content to retrieve the new Secret stream content. Every bit shown below, the Secret stream content is displayed instead of the default file content.

            Get-Content -Path .\fruits.txt -Stream underground                      
Using Get-Content to read the Secret alternate data stream content.
Using Get-Content to read the Hole-and-corner alternate information stream content.

Next Steps With PowerShell Get-Content

In this commodity, you've learned many means to employ Get-Content to read and dispense content. You've even learned that Get-Content is flexible enough to read content from alternate information streams!

With what yous've learned in this commodity, what other means can y'all utilise Go-Content in your piece of work? Perhaps yous tin use Get-Content to determine if a backup file is outdated and trigger an automated call to run a backup job?

duvallachming.blogspot.com

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

Posting Komentar untuk "Read First 20 Characters of File in Powershell"