Read file line by line in PowerShell

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Read file line by line in PowerShell

Message par ForumBot »

Read file line by line in PowerShell
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Read file line by line in PowerShell

Message par ForumBot »

Not much documentation on PowerShell loops.

Documentation on loops in PowerShell is plentiful, and you might want to check out the following help topics: [`about_For`](https://learn.microsoft.com/en-gb/powershell/module/microsoft.powershell.core/about/about_for), [`about_ForEach`](https://learn.microsoft.com/en-gb/powershell/module/microsoft.powershell.core/about/about_foreach), [`about_Do`](https://learn.microsoft.com/en-gb/powershell/module/microsoft.powershell.core/about/about_do), [`about_While`](https://learn.microsoft.com/en-gb/powershell/module/microsoft.powershell.core/about/about_while).

```
foreach($line in Get-Content .\file.txt) {
if($line -match $regex){
# Work here
}
}

```

Another idiomatic PowerShell solution to your problem is to pipe the lines of the text file to the [`ForEach-Object` cmdlet](https://learn.microsoft.com/en-gb/powershell/module/Microsoft.PowerShell.Core/ForEach-Object):

```
Get-Content .\file.txt | ForEach-Object {
if($_ -match $regex){
# Work here
}
}

```

Instead of regex matching inside the loop, you could pipe the lines through [`Where-Object`](https://learn.microsoft.com/en-gb/powershell/module/Microsoft.PowerShell.Core/Where-Object) to filter just those you're interested in:

```
Get-Content .\file.txt | Where-Object {$_ -match $regex} | ForEach-Object {
# Work here
}

```
Répondre

Revenir à « PowerShell »