Powershell Read List of Computers From File and Run Command Write to File

With automation, reading data from a text file is a common scenario. Nigh programming languages have at least 1 manner 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 information into a PowerShell session.

The PowerShell Get-Content cmdlet is an indispensable tool when you need to use text files as 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 easily supports these scenarios!

How well-nigh following a log file in real-time? Yes, the PowerShell Get-Content tin do that, too!. Keep reading this article, and you volition learn how to employ the Get-Content cmdlet to read text files in PowerShell.

Prerequisites

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

  • You'll need a computer that is running on Windows x. This tutorial uses Windows x version 20H2. But don't worry, you'll exist okay with the Windows 10 version that you take.
  • You lot should have at to the lowest degree Windows PowerShell 5.1, or PowerShell 7.1 installed on your computer. Here PowerShell seven.1 is used, simply either volition version will piece of work!
  • You'll be writing and testing commands, then you'll need a code editor. The recommended editors are Windows PowerShell ISE, built-in to Windows, and Visual Studio Lawmaking (VSCode). This article uses VSCode.
  • It will also help if yous create a working directory on your estimator. The working binder can be anywhere you lot want. Nevertheless, you lot'll observe that the examples in this tutorial reside in the C:\demo folder.
  • To get started, y'all need some content! Create a file, in your working directory, with the name fruits.txt that includes ten dissimilar fruits for simplicity. You will exist using this text file in all the examples.
            cherry  drupe  apricot  papaya  raspberry  melon  peach  tangerine  cantaloupe  orange          

Don't know which PowerShell version you have? Visit the article How to Bank check 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 past default, returns each line of a text file as a string object. As a result, the collection of PowerShell objects becomes an array of cord objects.

The below code reads the contents of the fruits.txt file and displays the issue 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 Become-Content.

Get-Content reads and stores the content as an array, but how do you know that for sure? First, salve the content to a PowerShell object which y'all can so examine to determine the blazon.

            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 inside the object  $fruits.Count  Output the contents of the object to the panel  $fruits          

Looking at the screenshot below, the $fruits variable is an array that contains ten 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 equally an array.

Returning a Specific Line From a Text File

In the previous example, you've learned that the default Get-Content result is an array or a collection of objects. Each item in a collection corresponds to an index number, and PowerShell indexes typically starting time at cipher.

The screenshot beneath shows that there are 10 items in the string array. The array indexed the ten items from zero to 9.

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

To only display the 5th line of content, y'all'll need to specify the index number 4, enclosed in square brackets (known equally array annotation).

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

Y'all may notice that the Get-Content command is enclosed in a parenthesis. This notation tells PowerShell to run the control enclosed in the parenthesis first before other operations.

In the screenshot below, you'll see that the only returned result is raspberry, which is the item at alphabetize 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 final line? Thankfully, yous do not need to know the total number of lines. Instead, apply [-1] every bit the index, and Become-Content volition display only the terminal line of the file.

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

Limiting the Number of Top Results Returned by Become-Content

Utilize 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 control below reads the content and limits the result to three items.

            Get-Content .\fruits.txt -TotalCount 3                      

As y'all would wait, the result below displays but the top 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 top three results using the Get-Content command 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 tiptop results. Information technology is also possible to achieve the opposite with PowerShell Get-Content. Apply the PowerShell Tail parameter to read a specified number of lines from the stop of a file.

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

            Get-Content .\fruits.txt -Tail iv                      

Afterwards running the PowerShell tail control, the expected event volition be limited to the last 4 lines of content, as shown in the image below.

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 Get-Content Tail parameter.

The Tail parameter is often used together with the Wait parameter. Using the Await parameter keeps the file open up and checks for new content once every 2nd. The demonstration below shows the Tail and Await parameters in activeness. To exit Wait, use the central combination of CTRL+C.

            Go-Content -Path .\fruits.txt -Tail one -Wait                      
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

Yous may take noticed in previous examples that yous've been dealing with string arrays equally the PowerShell Get-Content output. And as you've learned so far, the nature of arrays allows you to operate on the content one detail at a time.

Arrays often work great simply tin make replacing strings more hard. The Raw parameter of Become-Content reads a file's unabridged content into a unmarried string object. Although the code beneath is the same equally used within the starting time 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  Brandish the type of the object  $fruits.GetType()  Retrieve the count of items inside the object  $fruits.Count  Output the contents of the object to the console  $fruits          

The screenshot below demonstrates that adding 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 yous have the contents of a file in a single string using the Raw parameter, what tin can you do with information technology? Possibly yous need to find and replace a string inside of that file'south content. In the example beneath, Become-Content reads the content of a file as a unmarried string. Then, using the replace operator, supervene upon a specific word with some other.

Related: Finding and Replacing Strings

            # Become the raw content of the text file $fruits = Get-Content .\fruits.txt -Raw # Display the content $fruits # Find and supersede the discussion 'apricot' with 'mango' $fruits -replace '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 single cord and replacing a word using the replace operator.

Read Content Only from Files that Matched a Filter

Exercise you lot have a binder full of files just demand to read the content of a select few? With PowerShell Get-Content, you do non 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, first, create a couple of files to read. As shown beneath, create the files in your working binder 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-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 Get-ChildItem C:\demo                      
Creating test .log files using Add-Content.
Creating test .log files using Add-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 whatsoever file ending with .log. The ending asterisk of the path parameter limits the reading of files to only the root directory.

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

As 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 Go-Content to limit the read files.

Related: Become-ChildItem: Listing Files, Registry, Certificates, and More equally I

Reading the Alternate Information Stream of a File

Until at present, you have been working exclusively with text files, but Get-Content tin can read data from the alternate data stream (ADS) of a file. Feel gratuitous to read more almost streams, simply you can recall of a stream equally 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 utilise to Get-Content when used with not-Windows operating systems.

Y'all tin see alternating data streams by running Get-Particular with the Stream parameter. When referencing a file using the Stream parameter, Go-Item returns a belongings called Stream as shown beneath. This default file content stream is represented with :$Data.

To demonstrate the default :$DATA stream, apply the Get-Particular cmdlet to display all available streams in the file fruits.txt. As shown beneath, Get-Item displays a single stream.

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

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

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

To demonstrate retrieving an alternating data stream using Get-Content, modify a file using Add-Content to add the new stream. Use Get-Item to show the new stream alongside the default :$DATA stream, equally seen in the below example.

            # Add together a new ADS named Secret to the fruits.txt file Add-Content -Path .\fruits.txt -Stream Secret -Value 'This is a hugger-mugger. No one should detect this.' Get-Item -Path .\fruits.txt -Stream *                      
Adding the Secret alternate data stream using Add-Content and displaying the new stream with Get-Item.
Adding the Secret alternate data stream using Add-Content and displaying the new stream with Get-Particular.

As but the :$DATA stream is read by default, apply the Stream parameter of Get-Content to remember the new Hugger-mugger stream content. Every bit shown below, the Secret stream content is displayed instead of the default file content.

            Go-Content -Path .\fruits.txt -Stream cloak-and-dagger                      
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 fifty-fifty learned that Get-Content is flexible enough to read content from alternate information streams!

With what y'all've learned in this commodity, what other means can you utilize Get-Content in your work? Maybe y'all can use Get-Content to make up one's mind if a backup file is outdated and trigger an automatic call to run a backup chore?

spenceunneville.blogspot.com

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

0 Response to "Powershell Read List of Computers From File and Run Command Write to File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel