How to Use Powershell Get-Content and ForEach With Examples

-

|

Introduction

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
Advertisements


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

Advertisements


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:

Conclusion

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

FEATURED POSTS

How to Add Bullet Points in Google Slides

How to Add Bullet Points in Google Slides (Android or iOS Apps or PC)

This Itechguide teaches you how to add bullet points in Google Slides. The guide offers steps to add bullet points in Google...
How to Create a Business Facebook Page without a Personal Account

How to Create a Business Facebook Page without a Personal Account

This Itechguide teaches how to create a business Facebook page without a personal account. There could be a...
How to Wrap Text in Google Sheets

How to Wrap Text in Google Sheets (from a PC or the Apps)

This Itechguide teaches you how to wrap text in Google Sheets. The guide offers steps to wrap text in Google Sheets from...
How to Change Birthday on Facebook

How to Change Birthday on Facebook (from the App or PC)

This Itechguide teaches you how to change birthday on Facebook. The guide contains steps to change birthday on Facebook from the Facebook...
Best Thrillers on Netflix

The 10 Best Thrillers on Netflix

The thrillers on Netflix is quite a large number of movies. Knowing the best thrillers to watch can be a challenge.

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

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...

BEST OF ITECHGUIDES

How to Change Network from Public to Private in Windows 10

Introduction This guide demos 2 methods to change network from public to private in Windows 10.
Update Windows 7 to Windows 10

How to Upgrade Windows 7 to Windows 10 (2 Methods)

Introduction This guide demos 2 methods to update Windows 7 to Windows 10 free: Update...
windows cannot be installed on this disk

How to Fix “Windows Cannot be Installed on this Disk” Error

Introduction If you try to install Windows 10 on a non-Windows formatted hard driver you may receive "Windows cannot...
RAID 3 (Redundant Array of Independent Disks) Explained

RAID 3 (Redundant Array of Independent Disks) Explained

What is RAID 3? RAID 3 is a RAID implementation that uses striping with a dedicated parity disk....
windows server 2016 recovery mode

How to Repair Windows Server 2016 Boot (“BootMgr is Missing”)

Introduction If you are reading this, your Windows Server 2016 is probably broken and you may need to repair...

ADVERTISEMENTS

RECENT POSTS

How to Logout of Amazon App

How to Logout of Amazon App (from Android, iPhone or Windows 10)

This Itechguide teaches you how to logout of Amazon app. The guide offers steps to logout of Amazon app for Android, for...
How to Turn off YouTube Notifications

How to Turn off YouTube Notifications (PC or YouTube Apps)

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

How to Change YouTube Thumbnail (PC or YouTube Studio App)

This Itechguide teaches you how to change YouTube thumbnail. The guide offers steps to change YouTube thumbnail from a PC or...
How to Add Bullet Points in Google Slides

How to Add Bullet Points in Google Slides (Android or iOS Apps or PC)

This Itechguide teaches you how to add bullet points in Google Slides. The guide offers steps to add bullet points in Google...
How to Change Shipping Address on Amazon

How to Change Shipping Address on Amazon

This Itechguide teaches you how to change shipping address on Amazon. The guide offers steps to change shipping address on Amazon:

MUST READ

How to Make a Line Graph in Google Sheets

How to Make a Line Graph in Google Sheets

Introduction You can represent your data visually using a line graph in Google Sheets. This guide demonstrates how to...
Install Active Directory Role in Server 2016 and Promote to DC

How to Install Active Directory Role in Server 2016 and Promote to DC

Introduction This guide demos how to install Active Directory in Server 2016. It also covers how to promote the...
powershell.exe -command

Powershell.exe Command: Syntax, Parameters and Examples

Introduction You may be wondering why write on Powershell.exe Command. Are there special commands for Powershell.exe? Yes! When you...
How to Add Administrator to Facebook Page

How to Add Administrator to Facebook Page

Introduction After creating a Facebook page you can assign page roles. There are different page roles you can assign...
Disable IPv6 in Windows 10

How to Disable IPv6 in Windows 10 (3 Methods)

Introduction This guide demos 3 methods to disable IPv6 in Windows 10: Disable IPv6 from...

LATEST DEALS

Exclusive Student Offer_Save 10% on selected Surface devices

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