This Itechguide teaches you how to combine PowerShell Get-Content with ForEach loop. You can use Get-Content to list the content of a text file, then use the ForEach statement to iterate the content of the text file.
Overview
There are 3 variants of PowerShell ForEach, starting with the ForEach statement and the ForEach Method. Additionally, there is the ForEach-Object Cmdlet.
This guide starts by discussing the Get-Content command – its syntax, parameters, and some examples. Then, in the remaining parts of the guide, you will learn how to use each the 3 variants of PowerShell ForEach and Get-Content.
For each variant of ForEach, I will discuss its syntax. Finally, I will show multiple examples of how to use the PowerShell ForEach variant and Get-Content.
Syntax, Parameters, and Examples
As I mentioned in my introduction, before you can use PowerShell ForEach to iterate the content of a file, you need to import the content of the text file into PowerShell first.
The Get-Content Cmdlet is used to list or import the content of a text file into PowerShell.
In this section, we will look at the syntax and parameters of Get-Content. I will end the section with some examples.
Syntax and Parameters of the Get-Content Command
The simplified syntax of Get-Content command is…
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. You must include the extension of the text file (.txt).
Get-Content Command Examples
The screenshot below is a list of servers. To import the content of the text file into PowerShell, I will run the command below…
Get-Content D:\PS-Tutorial\Itechguides\Itechguides-Servers.txt
The command displays the list of servers in the text file.
How to Use ForEach with Get-Content
In this section, you will learn how to pipe the result of Get-Content into ForEach Loop. Then, within the ForEach Loop block, perform specific tasks.
The section starts by discussing the syntax of PowerShell ForEach Loop.
Syntax of the ForEach Statement
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.
In the first section of this guide, I gave an example of how to import the content of a text file with Get-Content. Here is the command…
Get-Content D:\PS-Tutorial\Itechguides\Itechguides-Servers.txt
If we include this in the ForEach Statement syntax, the ForEach statement will be updated as shown below:
ForEach ($item in (Get-Content D:\PS-Tutorial\Itechguides\Itechguides-Servers.txt)) { Perform a task based on a powershell command }
In the updated ForEach statement syntax, I replaced the $collection variable with Get-Content D:\PS-Tutorial\Itechguides\Itechguides-Servers.txt command.
Moreover, we can save this command in the $collection variable…
$collection = Get-Content D:\PS-Tutorial\Itechguides\Itechguides-Servers.txt
Then, we can use the simplified version of the ForEach statement syntax…
ForEach ($item in $collection) { Perform a task based on a powershell command }
To learn more about this powerful PS statement, click PowerShell ForEach: Syntax, Parameters, Examples.
In the remaining subsections of this section, I will give more examples.
How to Iterate a Text File with ForEach Loop
In this sub-section, I will add some commands to the command block of the ForEach statement. Here are the updated commands.
$collection = Get-Content D:\PS-Tutorial\Itechguides\Itechguides-Servers.txt ForEach ($item in $collection) { write-host $item }
If I run the script in PowerShell ISE, it displays the content of the text file.
How to Combine Get-ChildItem, ForEach Loop, and Get-Content
If you have multiple text files in a folder, you need to first get the full path to the text files. To get the full path of the text files, you need the Get-ChildItem command.
To illustrate this, I created two text files in a folder. See the screenshot below…
As I mentioned eelier, the first step is get the path to all the text files in the folder. Here is the command that does this job…
(Get-ChildItem D:\PS-Tutorial\Itechguides).FullName
The command lists the full path to the text files…
However, if you have other items in the folder, for instance subfolders and other types of files, you need to improve the command to return only text files…
$textfiles = (Get-ChildItem D:\PS-Tutorial\Itechguides | Where-Object {$_.Extension -eq '.txt'}).FullName
Now that we have the paths to all the text files in the folder, the next step is to use Get-Content to list the contents of each text file. However, because there is more than one text file, we need to use ForEach statement.
$textfiles = (Get-ChildItem D:\PS-Tutorial\Itechguides | Where-Object {$_.Extension -eq '.txt'}).FullName ForEach ($textfile in $textfiles) { Get-content $textfile }
Here is the result of the script in PowerShell ISE…
How to Create Folders with the Content of a Text File
In this sub-section, you will learn how to create folders with the content of a text file.
To demonstrate this, I have a text file with names.
I will use Get-Content to import the content of the text file into PowerShell; then use ForEach statement block to iterate the contents of the text files.
Finally, within the ForEach statement block, I will use makdir command to create folders with the content of the text file.
However, instead of separating the commands like we have done so far, I will combine all the commands. Here is the script…
ForEach ($filename in Get-Content D:\PS-Tutorial\list.txt) {cd "D:\PS-Tutorial";mkdir $filename}
In this command, I used Windows Command Prompt commands, cd and mkdir. Here is the PowerShell version of the command…
ForEach ($filename in Get-Content D:\PS-Tutorial\list.txt) { New-Item -Path "D:\PS-Tutorial" -Name $filename -ItemType Directory }
And here is the result in PoweShell ISE:
Alternatively, if you do not want the information about the created folders displayed, pipe the output of the New-Item command to Out-Null.
The script will now look like this…
ForEach ($filename in Get-Content D:\PS-Tutorial\list.txt) { New-Item -Path "D:\PS-Tutorial" -Name $filename -ItemType Directory | Out-Null }
Splitting and Joining the Content of a Text File with ForeEach Statement
While I was researching this article, I came across this Stackoverflow.com question. The person that asked the question has a text file with the following strings:
80055555|Lastname|Firstname|AidYear|DCDOCS|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf
However, the person wants to modify the strings to look like this:
80055555|DCDOCS|Lastname|Firstname|AidYear|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf
To replicate this situation, I created a text file with the original strings. Then, I created a short script that will achieve the required result.
Here is the script.
$file = "D:\PS-Tutorial\filelist.txt" $filecontent = Get-Content $file $newfile = ForEach($line in $filecontent){ ($line.split('|'))[0,4,1,2,3,5] -Join '|' } $newfile | Set-Content $file
The first and second line are relatively straightforward. In line 1, I saved the text file path to a variable.
Then, in line 2, I used Get-Content to import the content of the text file into PowerShell and save the result in another variable.
Finally, in lines 3, 4, and 5 I used the result of the Get-Content command in a PowerShell ForEach Statement. I saved the result of the ForEach Statement in another variable.
The most important of the ForEach Statement is what I have in the command block…
($line.split('|'))[0,4,1,2,3,5] -Join '|'
The first part of the command uses PowerShell Split Method to “break” the content of the text file. Here is the command…
($line.split('|'))
What this command does is “break” the strings in the text file at the “|” character. To help you relate to this, here are the original strings in the text file.
80055555|Lastname|Firstname|AidYear|DCDOCS|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf
The result of the split command creates the following individual strings:
80055555 Lastname Firstname AidYear DCDOCS D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf
When PowerShell split creates individual strings like this, each item is represented by a position number, starting from 0 (zero). So, you can access the first string, 80055555 with [0], the second with [1], and so on.
Before I explain the next part of the command, let’s see the output we want to achieve. Here it is…
80055555|DCDOCS|Lastname|Firstname|AidYear|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf
If we were to “break” this output with PowerShell Split, we will achieve this…
80055555 DCDOCS Lastname Firstname AidYear D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf
If you compare this to the result when we split the original string, you notice that the substring in position 4 of the original text file (DCDOCS) is now in position 2. Every other substring retained its original position.
This is where the job of the second bit of the command shown…
[0,4,1,2,3,5]
This command simply means…
80055555,DCDOCS,Lastname,Firstname,AidYear,D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf
So far I have explained this command..
($line.split('|'))[0,4,1,2,3,5] -Join '|'
Up to this point…
($line.split('|'))[0,4,1,2,3,5]
The final bit uses PowerShell Join Operator to insert the original character “|”, between the new string created by this command…
[0,4,1,2,3,5]
In the last few paragraphs I have explained line 4 of this script.
$file = "D:\PS-Tutorial\filelist.txt" $filecontent = Get-Content $file $newfile = ForEach($line in $filecontent){ ($line.split('|'))[0,4,1,2,3,5] -Join '|' } $newfile | Set-Content $file
Finally, in line 6, I piped the output of the new string saved in newfile variable into Set-Content. Set-Content overwrites the original file with the new string.
This is a brilliant example of how you can combine Get-Content with PowerShell ForEach statement!
How to Use ForEach Method with Get-Content
The ForEach Method was introduced in PowerShell version 4. This method gives PowerShell script developers another way to iterate the content of a text file.
In this section, you will learn how to Use ForEach Method with Get-Content with mulrtiple examples.
The section starts with the syntax of the ForEach Method.
Syntax Of PowerShell ForEach Method
The syntax of PowerShell ForEach Method is…
(<object list>).ForEach ({ <Perform a tasks based on PowerShell statemements in this block> } )
Accessing the ForEach Method of an object is similar to accessing any other PowerShell Method. The only differennce is that the ForEach Method includes a {} block within the () block.
How to Combine Get-ChildItem, ForEach Method and Get-Content
In the ForEach Statement section of this guide, I shared the script below…
$textfiles = (Get-ChildItem D:\PS-Tutorial\Itechguides | Where-Object {$_.Extension -eq '.txt'}).FullName
ForEach ($textfile in $textfiles) {
Get-content $textfile
}
The script used Get-ChildItem to return the full path to the text files in this folder…
Here is the ForEach Method equivalent script…
$textfiles = (Get-ChildItem D:\PS-Tutorial\Itechguides | Where-Object {$_.Extension -eq '.txt'}).FullName $textfiles.ForEach({ Get-content $_ } )
How to Create Folders with the Content of a Text File with ForEach Method
Similar to the example in the last subsection, I used the script below in the ForEach Statement section of this guide…
ForEach ($filename in Get-Content D:\PS-Tutorial\list.txt) {
New-Item -Path "D:\PS-Tutorial" -Name $filename -ItemType Directory | Out-Null
}
The script used Get-Content and ForEach Statement to create folders using the content of the text file in the screenshot below…
Unlike the ForEach Statement that uses the command…
ForEach ($filename in Get-Content D:\PS-Tutorial\list.txt)
PowerShell ForEach Method calls the ForEach Method in the result of Get-Content like this…
(Get-Content D:\PS-Tutorial\list.txt).ForEach()
Then, within the () block, we insert {} block and run the New-Item command. However, instead of using the $filename variable, this time, I use the $_ automatic variable
New-Item -Path "D:\PS-Tutorial" -Name $_ -ItemType Directory | Out-Null
The final ForEach Method version of the scrip looks like this…
(Get-Content D:\PS-Tutorial\list.txt).ForEach( { New-Item -Path "D:\PS-Tutorial" -Name $_ -ItemType Directory | Out-Null } )
This time, I want to run the command in PowerShell, instead of PowerShell ISE. So, I will have the whole script in a single line…
(Get-Content D:\PS-Tutorial\list.txt).ForEach({New-Item -Path "D:\PS-Tutorial" -Name $_ -ItemType Directory | Out-Null })
Here is the command in PowerShell and the folders created. I have also included the screenshot of the text file with the folder names…
Splitting and Joining the Content of a Text File with ForeEach Method
In the ForEach Statement section of this guide, I gave an example with this Stackoverflow.com question. The person that asked the question wants to modify the following string in a text file…
80055555|Lastname|Firstname|AidYear|DCDOCS|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf
To this…
80055555|DCDOCS|Lastname|Firstname|AidYear|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf
To fix the problem, I created this script that uses Get-Content and PowerShell ForEach statement…
$file = "D:\PS-Tutorial\filelist.txt" $filecontent = Get-Content $file $newfile = ForEach($line in $filecontent){ ($line.split('|'))[0,4,1,2,3,5] -Join '|' } $newfile | Set-Content $file
In this section of the guide we are discussing how to use Get-Content and ForEach Method, here is the equivalent script with ForEach Method…
$file = "D:\PS-Tutorial\filelist.txt" $filecontent = Get-Content D:\PS-Tutorial\filelist.txt $newfile = $filecontent.ForEach({ ($_.split('|'))[0,4,1,2,3,5] -Join '|' ) } $newfile | Set-Content $file
The modified is the same except that, in this modified version, I replaced ForEach statement with ForEach Method.
How to Use ForEach-Object Cmdlet with Get-Content
In this last section, I will repeat some of the examples I have already given in the first two sections.
However, in this section, I will be replacing the ForEach statement and/or ForEach Method with ForEach-Object Cmdlet.
The section starts with the syntax of the ForEach-Object Cmdlet
Syntax of ForEach-Object Cmdlet
There are two syntaxes of ForEach-Object. Here are their simplified versions:
ForEach-Object [-MemberName] [-InputObject]
ForEach-Object [-Process] [-Begin] [-End] [-InputObject]
The syntaxes of ForEach-Object may appear complex. However, it is very easy to use. For this guide, we will focus on the InputObject parameter.
This is the parameter that feeds input into ForEach-Object. Moreover, InputObject may also be sent via a pipeline…
<InputObject > | ForEach-Object
How to Create Folders with the Content of a Text File with ForEach-Object Cmdlet
In the first and second sections of this guide, I created the following scripts.
ForEach ($filename in Get-Content D:\PS-Tutorial\list.txt) {
New-Item -Path "D:\PS-Tutorial" -Name $filename -ItemType Directory | Out-Null
}
(Get-Content D:\PS-Tutorial\list.txt).ForEach( { New-Item -Path "D:\PS-Tutorial" -Name $_ -ItemType Directory | Out-Null } )
The first script uses the Get-Content ForEach Statement to create folders using the content of the text file in the screenshot below…
Additionally, the second script uses Get-Content ForEach Method to perform the same task.
If you want to use ForEach-Object Cmdlet instead of ForEach Statement or ForEach Method, the script will be modified as shown below…
Get-Content D:\PS-Tutorial\list.txt | ForEach-Object { New-Item -Path "D:\PS-Tutorial" -Name $_ -ItemType Directory | Out-Null }
Splitting and Joining the Content of a Text File with ForEach-Object Cmdlet
In the ForEach Statement and ForEach Method sections, I created the following scripts to fix this Stackoverflow.com question.
$file = "D:\PS-Tutorial\filelist.txt" $filecontent = Get-Content $file $newfile = ForEach($line in $filecontent){ ($line.split('|'))[0,4,1,2,3,5] -Join '|' } $newfile | Set-Content $file
$file = "D:\PS-Tutorial\filelist.txt" $filecontent = Get-Content D:\PS-Tutorial\filelist.txt $newfile = $filecontent.ForEach({ ($_.split('|'))[0,4,1,2,3,5] -Join '|' ) } $newfile | Set-Content $file
Here is the ForEach-Object Cmdlet version of the same script:
$file = "D:\PS-Tutorial\filelist.txt" $filecontent = Get-Content D:\PS-Tutorial\filelist.txt $newfile = $filecontent | ForEach-Object { ($_.split('|'))[0,4,1,2,3,5] -Join '|' } $newfile | Set-Content $file
Conclusion
The topics shared in this guide may be confusing, especially because it covered 3 variants of PowerShell ForEach. To make it easy to understand, here is a table summarizing the concepts shared in this article.
Question | ForEach Statement | ForEach Method | ForEach-Object Cmdlet |
---|---|---|---|
Accepts Input from Get-Content | ✓ | ✓ | ✓ |
How does it accept input from Get-Content? | Pipeline “|”, or within the ForEach Statement condition block | PowerShell Method “.()” | Pipeline “|” or via the InputObject parameter |
How does it transform the input from Get-Content? | Creates a temporal variable that represents each object in the collection | Represents each object in the collection with PowerShell automatic pipeline variable, $_ | Represents each object in the collection with PowerShell automatic pipeline variable, $_ |
Sample Script? | ForEach ($filename in Get-Content D:\PS-Tutorial\list.txt) { New-Item -Path “D:\PS-Tutorial” -Name $filename -ItemType Directory | Out-Null } | (Get-Content D:\PS-Tutorial\list.txt).ForEach( { New-Item -Path “D:\PS-Tutorial” -Name $_ -ItemType Directory | Out-Null } ) | Get-Content D:\PS-Tutorial\list.txt | ForEach-Object { New-Item -Path “D:\PS-Tutorial” -Name $_ -ItemType Directory | Out-Null } |
That is it – our updated guide about how to use PowerShell Get-Content and ForEach! I hope you found it helpful?
If you found it helpful, we would appreciate 2 minutes of your time to share your experience by responding to the “Was this page helpful?” question below.
Finally, for more PowerShell tech Itechguides, visit our Windows PowerShell How-To guide page. You may also find our Work from Home page very helpful.
I have a script that checks each line of a log but I need to check two conditions on that line is there a simple way to do this ? for example on each line there is a time stamp followed by a message. I need to verify a recent timestamp and then that the message states connected.
$logDirectoy = $env:USERPROFILE + ‘\AppData\Local\Temp\’
$logFile = ‘logterminal.txt’
$logStorageFolder = ‘F5Logs’
# Set log directory to the current working directory.
Set-Location $logDirectoy
# Comment out when not testing locally.
# if (!(Test-Path $logFile)) {
# New-Item $logFile
# }
# If the storage folder does not exist create it.
if (!(Test-Path $logStorageFolder)) {
New-Item -path $logStorageFolder -ItemType Directory
}
# If the log file exists in the current directory move it to the storage folder.
if (Test-Path $logFile) {
$fileCount = (Get-ChildItem $logStorageFolder).Count
$newLogName = “logterminal.$fileCount.txt”
Rename-Item $logFile $newLogName
Move-Item $newLogName $logStorageFolder
}
# Create a fresh log file.
if (!(Test-Path $logFile)) {
New-Item $logFile
}
# Open VPN
Start-Process -filepath “launches vpn client”
# Loop while connected message is not detected and continue once it is.
$connected = $false
while (!$connected) {
foreach($line in Get-content $logFile) {
$status = Select-String -Pattern ‘User status is:\s*(\S+)’ -InputObject $line
if ($status -match ‘connected’) {
$connected = $true
Write-Host ‘VPN Connection Detected’
}
}
}
Start-process -filepath “launches vpn required systems”
Detailed explanation really helped. Thank you