How to Use Powershell Get-Content and ForEach With Examples

-

|

You can combine Powershell Get-Content and ForEach Loop in so many Windows automation tasks.

Here is how it works: list the contents of the text file with Get-Content. Then perform a specific task on each item in the text file by passing them through the ForEach statement loop.

This guide demos how to use Powershell Get-Content and ForEach to iterate the contents of a file.

The guide is broken down into 4 sections:

  1. Get-Content Syntax and Parameters
  2. ForEach Syntax and Parameters
  3. How to Use Powershell Get-Content and ForEach
  4. Powershell Get-Content and ForEach Example

1
Get-Content: Syntax and Parameters

The Get-Content Cmdlet gets the content of the item at the specified location.

Here is the simplified syntax of this Cmdlet:

Get-Content [-Path] <String[]> 

Get-Content has a lot more parameters. I specified the commonly used parameters.

Use the -Path parameter to specify the full path (<String[]>) to the text file, including the extension.

You do not have to specify the -Path parameter before you enter the path to the text file.

As an example to list the contents of the text file in this path “C:\PS\file with UserNames.txt”, use the command below:

Get-Content "C:\PS\file with UserNames.txt"

The command returns the contents of the text file:

To add the result to a variable, use this command

$UserNames = Get-Content "C:\PS\file with UserNames.txt"

The result is not displayed on the console because it is stored in the $UserNames variable.

2
ForEach Statement: Syntax and Parameters

A PowerShell ForEach Statement performs an operation against each item in a collection of input objects. For the purpose of this guide, the operation will be performed against the items in a text file.

The syntax of ForEach Statement is:

ForEach ($item in $collection) {Perform a task based on a powershell command}  

As expected, the syntax will begin with ‘ForEach’. It is then followed by a by brackets ‘()’; and finally ‘{}’ block.

To continue with the Get-Content example, to use ForEach to loop through the contents stored in the $UserNames use this command:

ForEach ($User in  $UserNames ) {

#Perform an operation

}

I will continue with this example in section 3rd and 4th sections of this guide.

We have a full guide covering ForEach. To learn more about this powerful PS statement, click ForEach Statement.

3
How to Use Powershell Get-Content With ForEach

In section 2, I gave this command as an example:

ForEach ($User in $UserNames) {

#Perform an operation

}

If you recollect, $UserNames variable contains the result of this command:

Get-Content "C:\PS\file with UserNames.txt"

Which is:

powershell get-content foreach

To confirm that $UserNames saved the values, type the variable in PowerShell. Then press enter:

$UserNames 

Here they are!

powershell get-content foreach

Now lets go back to the command that combined Powershell Get-Content and ForEach

ForEach ($User in $UserNames) {

#Perform an operation

}

Here is this command simplified in plain English:

“ForEach ($User in $UserNames)” simply tells PowerShell to take the first item in the list ($UserNames) and make it the variable $User. Then perform the operation in the {} block on the item stored in the $User variable.

It then circles back and takes the next item in $UserNames and stores it in $User variable. Then perform the operation within the {} block again.

ForEach will keep doing this until the last item in the $UserNames variable. Then it will terminate.

4
Powershell Get-Content and ForEach Example

In the last section, I explained how ForEach takes each result of Get-Content and performs an operation on the item.

Here is the command:

ForEach ($User in $UserNames) {

#Perform an operation

}

Your next question may be “what type of operation can I perform in the {} part of ForEach”. The answer is: any task that PowerShell can perform!

Here are some examples:

  • Delete the contents of the file that meet a particular criteria
  • Replace the contents of the file
  • Create or modify AD Users with the contents of the file

In my final example in this guide, I will simply write a sentence with each item in the text file. The statement will be ‘$User is in the text file’.

Here is the script

$UserNames = Get-Content "C:\PS\file with UserNames.txt"

ForEach ($User in $UserNames) {

Write-Host "$User is in the text file"

}

…and the result in PowerShell ISE:

The examples in this guide are intentionally over simplified. The aim is to make it easy for you to understand how to use Powershell Get-Content and ForEach. I hope I succeeded!

Have a question or comment? Use the “Leave a Reply” form found at the end of this page.

Want more PowerShell guides? Visit our PowerShell Windows PowerShell page.

  • Was this post Helpful?
  • YesNo

LEAVE A REPLY

Please enter your comment!
Please enter your name here

ADVERTISEMENTS

FEATURED POSTS

How to Share Amazon Wish List

How to Share Amazon Wish List

This Itechguide teaches you how to share Amazon Wish List. The guide covers steps to share Amazon Wish List from a PC...
How to Pay with PayPal on Amazon

How to Pay with PayPal on Amazon

This Itechguide teaches you how to pay with PayPal on amazon. The guide covers 2 options to pay with PayPal on amazon....
How to Export Contacts from Outlook

How to Export Contacts from Outlook

This Itechguide teaches you how to export contacts from Outlook. The guide covers steps to export contacts from Outlook (Windows 10) or...
Best 90s Movies on Netflix

The 10 Best 90s Movies on Netflix

This Itechguide reviews the 10 best 90s movies on Netflix. The movies are listed in reverse order – with the 10th movie...
How to Clear Search History on Instagram

How to Clear Search History on Instagram

This Itechguide teaches you how to clear search history on Instagram. The guide covers steps to clear search history on Instagram from...

AMAZON DEALS

TRENDING POSTS

Remote Desktop Connection

Remote Desktop Connection an Internal Error Has Occurred [Fixed]

Introduction I recently received the error message "Remote Desktop Connection an Internal Error Has Occurred". It was strange because...

Find My Samsung: Register and Use Samsung Find my Mobile

Introduction Ever wondered how you could find your Samsung phone if you lost it? Find my Samsung or Samsung...
What is the Difference Between PowerShell and CMD?

Windows Powershell vs CMD: Differences and Similarities

Introduction This short guide compares Windows PowerShell vs CMD (Windows command prompt). I will cover the history and nature...
Spotify No Longer Supports this Version of Microsoft Edge

Spotify No Longer Supports this Version of Microsoft Edge [Fixed]

Introduction When you open Spotify web player on Microsoft Edge, you may receive the error message "Spotify No Longer...
Windows 10 Won't Boot

Windows 10 Won’t Boot With Black Screen? 3 Ways to Fix It

Why Won't Windows 10 Boot Up? If your Windows 10 stops with a black screen, the first question in...

ADVERTISEMENTS

BEST OF ITECHGUIDES

RAID 50

RAID 50 vs RAID 10: Benefits and Disadvantages Compared

What is RAID 50 vs RAID 10? RAID 50 stripes two RAID 5 arrays while RAID 10 stripes two...
Best Christian Movies on Netflix

The 10 Best Christian Movies on Netflix

This Itechguide reviews the 10 best christian movies on Netflix. The movies are listed in reverse order – with the 10th movie...
How to Alphabetize in Google Sheets

How to Alphabetize in Google Sheets

This Itechguide teaches you how to alphabetize in Google Sheets. The guide covers steps to alphabetize in Google Sheets from a PC...
Chrome ADMX

How to Download and Install Google Chrome Administrative Template

Introduction To configure Google Chrome settings via Group Policy you require Chrome ADMX. However, as you would expect by...
How to Turn off YouTube Notifications

How to Turn off YouTube Notifications

This Itechguide teaches you how to turn off YouTube notifications. The guide offers steps to turn off YouTube notifications from a PC...

RECENT POSTS

5 Best Bluetooth Headphones Under 100

5 Best Bluetooth Headphones Under $100

This Itechguide reviews the 5 best Bluetooth headphones under 100 (USD). The best headphone is reviewed last, starting with the 5th on...
How to Search for a Word in Google Docs

How to Search for a Word in Google Docs

This Itechguide teaches you how to search for a word in Google Docs. The guide covers steps to search for a word...
How to Create a Folder in Google Docs

How to Create a Folder in Google Docs

This Itechguide teaches you how to create a folder in Google Docs. The guide covers steps to create a folder in Google...
How to Check Amazon Gift Card Balance

How to Check Amazon Gift Card Balance

This Itechguide teaches you how to check Amazon gift card balance. The guide covers steps to check Amazon gift card balance from...
How to Remove Google Account from Phone

How to Remove Google Account from Phone

This Itechguide teaches you how to remove Google Account from phone. The guide covers steps to remove Google Account from Android or...

AMAZON DEALS

MUST READ

Best Wireless Surround System

The 10 Best Wireless Surround Sound Systems

This Itechguide reviews the 10 best wireless surround sound system. The sound systems are listed in reverse order with the 10th best...
How to Change Theme Colors in Google Slides

How to Change Theme Colors in Google Slides

This Itechguide teaches you how to change theme colors in Google Slides. The guide covers steps to change theme colors in Google...
SysWOW64 and File System Redirector Explained

SysWOW64 and File System Redirector Explained

Introduction A Windows 64-bits OS has a SysWOW64 folder. It also has a System32 folder. These folders contain OS...
powershell replace

PowerShell Replace “Method” and “Operator”: Syntax, Examples

Introduction PowerShell Replace can be used to replace character strings, texts or special characters. PowerShell has a Replace...
How to Print Google Calendar

How to Print Google Calendar

This Itechguide teaches you how to print Google Calendar. The guide covers steps to print Google Calendar to paper and to PDF...

AMAZON DEALS

By using this website you agree to accept our Privacy Policy and Terms & Conditions