|

FEATURED POSTS

How to Change Outlook Password in 3 Different Ways

How to Change Outlook Password in 2 Easy Steps

Introduction Before you change your Outlook Password you have to first change it with your email provider. The reason...
spotify web player not working

Spotify Web Player Not Working [Fixed]

Introduction Spotify Web Player may stop working for you with the following error messages: "Spotify Web Player an Error...
DISM.exe /Online /Cleanup-Image /Restorehealth

DISM.exe /Online /Cleanup-Image /Restorehealth Explained

What is DISM.EXE /Online /Cleanup-image /RestoreHealth? "DISM.exe /Online /Cleanup-Image /Restorehealth" is a DISM command that repairs issue with the...
DHCP Relay agent

DHCP Relay Agent: Configuration in Windows Server 2016

What is a DHCP Relay Agent? A DHCP Relay Agent allows DHCP clients in a different network subnet to...
ForEach-Powershell

PowerShell ForEach: Syntax, Parameters, Examples

What is PowerShell ForEach? PowerShell ForEach (ForEach PowerShell) is a PowerShell construct used in iterating through values in a...

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...
PowerShell vs CMD

Powershell vs CMD: Differences and Similarities Compared

Introduction This short guide compares PowerShell vs CMD (Windows command prompt). I will cover the history and nature of...
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 Convert Text to Number in Excel

How to Convert Text to Number in Excel in 4 Easy Ways

Introduction There are 4 ways you can convert text to number in Excel. This guide demonstrates the 4 ways...
inaccessible boot device server 2016 fix

How to Fix Inaccessible Boot Device Error in Windows Server 2016

Introduction Some Windows admins have reported receiving "inaccessible boot device" error in Server 2016 after a Windows update. If...
most useful powershell commands

18 Most Useful Powershell Commands for Windows Admins

Introduction This guide will cover 18 most useful powershell commands for sys admins. PowerShell commands,...
GPResult Command

GPRESULT Command: Syntax, Parameters, Examples

What is GPRESULT? GPRESULT is a command line tool that displays the Resultant Set of Policy (RSoP) information for...
Dual Boot Windows 7 and 10

Dual Boot Windows 7 and 10: Step by Step Guide

Introduction Want to try Windows 10 without upgrading? One option is to dual boot windows 7 and 10. ...

RECENT POSTS

how to merge cells in excel

How to Merge Cells in Excel in 2 Easy Ways

Introduction You can merge two Cells in Excel using CONCATENATE function or the “&” (ampersand) operator. Though Excel has...
How to Make a Pivot Table in Google Sheets

How to Make a Pivot Table in Google Sheets

Introduction You can make a Pivot Table in Google Sheets to simplify analysis of complex data. A Pivot Table...
how to make Pivot Table

How to Make a Pivot Table in Excel

Introduction A Pivot Table allows you to analyze, summarize and calculate large data to help find relationships. With a...
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....
RAID 5 vs RAID 6

RAID 5 vs RAID 6: Differences, Benefits and Disadvantages

What is RAID 5 vs RAID 6? RAID 5 and RAID 6 uses striping with distributed parity technique. However,...
concatenate excel

Concatenate in Excel: How to Concatenate Columns and Strings

What is Concatenate in Excel? Concatenate in Excel is joining two strings into one continuous string. You can join...

How to Add in Excel (Excel Sum) with Examples

Introduction There are different ways to add numbers in Excel. You could simply select the cells containing the data....
Excel Count

Excel Count: How to Count in Excel With Examples

Introduction Excel COUNT Function is used for counting items in a worksheet. Excel COUNT also has the conditional function,...
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 move columns in excel

How to Move Columns to Rows and Rows to Columns in Excel

Introduction If you receive some Excel data in columns, you can easily move the columns to rows in Excel...

MUST READ

How to Convert Text to Number in Excel

How to Convert Text to Number in Excel in 4 Easy Ways

Introduction There are 4 ways you can convert text to number in Excel. This guide demonstrates the 4 ways...
How to Make a Pivot Table in Google Sheets

How to Make a Pivot Table in Google Sheets

Introduction You can make a Pivot Table in Google Sheets to simplify analysis of complex data. A Pivot Table...
Sort Gmail by Size

How to Sort Gmail by Size Using Gmail Search

Introduction If you are running out of space, you may want to sort Gmail by size so you can...
Windows Cannot Find GPEDIT.MSC or GPEDIT.MSC Not Found [Fixed]

Windows Cannot Find GPEDIT.MSC or GPEDIT.MSC Not Found [Fixed]

Introduction If you try opening gpedit.msc from Windows 10 Home you will receive the error message windows cannot find...
Windows defender blocked by Group Policy

Windows Defender Blocked by Group Policy [Fixed]

Introduction If you receive the error message Windows Defender is blocked by group policy, your computer may have been...

How to Iterate the Content of a Text File in Powershell in 2 Easy Ways

-

Introduction

If you have a text file with data you wish to use, you can use PowerShell Get-Content to list the contents of the file. Then use PowerShell ForEach to loop through the file line by line.

An example could be a list with Active Directory user names in a text file. You can use the usernames from the text file to search for the users in AD, then update other user information in AD.

Another simple application of PowerShell ForEach is to loop through the content of a file and append a text to each line. More in examples section of this guide.

In this quick guide, I present 2 easy ways you can do this using Get-Content, ForEach loop, and ForEach-Object.

Advertisement

How to Use PowerShell ForEach Loop and Get-Content to Iterate Through a File

Before discuss how to use ForEach and Get-Content to loop through a file in Powershell, let me show you the Syntax of both commands:

Syntax of ForEach:

ForEach ($file in $files) {Run the command in this block}

In the context of this guide, here is what each parameter means:

$files are the contents of the text file.
$file is used to take one line at a time and perform the command in the block, {}.
{} contains the command that is run on each line in the file.

Here is the simplified Syntax of Get-Content cmdlet:

Get-Content -Path <path to text file>

We can combine both command to product the syntax of powershell foreach $file in $files below:

ForEach ($file in (Get-Content -Path <path to text file>)) {Run the command in this block}

Powershell ForEach $file in $files Example

The first step in iterating through a text file with Powershell ForEach is to get the contents of the file with Get-Content. Here is the command:

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

And the result in PowerShell:

foreach in file powershell - Get-Content "C:\PS\file with numbers.txt"

The next step is to add Get-Content “C:\PS\file with numbers.txt” into the ForEach $file in $files loop. Here is the command:

ForEach ($file in (Get-Content "C:\PS\file with numbers.txt")) {Run the command in this block}

Finally, I will add a command into the command block, {}. In this example, I want PowerShell to display “This is line xx”.

Here is the command I will include in the {} block.

Write-Host "This is line $file in the text file"

And now the final ForEach ($file in $files) command:

 ForEach ($file in (Get-Content "C:\PS\file with numbers.txt")) {

Write-Host "This is line $file"

}

Here is the result in PowerShell ISE:

To make it easy to understand the above result, here is the result of the Get-content part.

So, what the ForEach ($file in $files) command command did was to append “This is line ” at the beginning of each $file. $file being each line item in the text file.

How to Use PowerShell ForEach-Object and Get-Content to Iterate Through a File

Another way you can loop through the content of a text file is to use the ForEach-Object cmdlet. This time, you will pipe the output of Get-Content to ForEach-Object cmdlet.

Continuing with the previous example, here is the command:

Get-Content "C:\PS\file with numbers.txt" | ForEach-Object {
Write-Host "This is line $_"
}

This is the result of the above command in PowerShell ISE:

foreach in file powershell - ForEach-Object

There is one difference between the above command and the ForEach ($file in $files) command. While the ForEach command assigns each content of the text file a variable, $file during the iteration, the ForEach-Object command assigns a variable, $_

In PowerShell “$_” is the variable for the current value in the pipe line. In this example, the output of Get-Content is stored in the variable, $_
Advertisement

Conclusion

You arrived at this guide because you likely searched for “foreach in file powershell” or its variant. I hope I have been able to answer your question on how to iterate through the content of a file with either ForEach ($file in $files) in PowerShell or ForEach-Object.

If you have any question use the “Leave a Reply” form at the end of the page. Alternatively, you could share your experience using PowerShell ForEach to work with files.

Other Helpful Guides

Additional Resources and References

YOU MAY ALSO LIKE:

LEAVE A REPLY

Please enter your comment!
Please enter your name here

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