Glam Prestige Journal

Bright entertainment trends with youth appeal.

A lot of the questions around the internet for this specific topic are oriented into BASH for linux, I was wondering if the same thing can be achieved using just PowerShell.

On Bash, one can use:

for line in $(cat file.txt); do echo $line; done

And then bash will loop through each line of file.txt and send it to echo or whatever command you're using.

How can the same thing be achieved on Windows's powershell?

I found that PS has the "Get-Content" command that works similarly to "cat", but I couldn't continue from there.

2 Answers

Ok it turns out that it was not that difficult but I'll leave it here for the future people of the internet.

PowerShell has a defined set of Loops, one of them called ForEach
One can simply do:

ForEach ($line in Get-Content [File]) {[Command]) $line}

Where [File] is the file path you're reading from and
Where [Command] is the command you're sending each line into.

Just as an example:

ForEach ($line in Get-Content thingstoecho.txt) {echo $line}

An alternative to your answer, which reads the entire file before passing the first line for subsequent processing, is to leverage the pipeline and begin processing once the first line is read.

Get-Content thingstoecho.txt | ForEach-Object { echo $_ }

For smaller files, the difference can be trivial. But for large datasets, the pipeline appraoch is less likely to strain resources as it doesn't try to hold the entire file in memory at one time.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy