powershell for loop help

rated by 0 users
This post has 4 Replies | 1 Follower

Top 500 Contributor
Posts 3
Terrell Posted: 03-09-2011 1:05 PM

Hey Guys,

I'm having some issues consructing the correct for loop I need and also finding a command to e-mail output. Maybe you guys can help me. 

Currently I have a directory listing that has been parsed and stripped of everything except for the file name and dumped into a file called listing.txt. so, currently the file looks something like this:

test1.txt

test2.txt

test3.txt

Basically I'm trying to write a for loop that will read each line inside of listing.txt and run a get-content(or cat) for each line. I would then need it to take that output and send it as an e-mail so for example, If I were to write this in bash it would look something like the following:

 

for line in `cat listing.txt`;do

echo "$line" >> output.txt

cat "$line" >> output.txt

echo "" >> output.txt

mail -s "this is a subject" test@yahoo.com < output.txt

done

 

Hopefully you guys can help me, as I'm totally new to powershell. Thanks alot!

-Terrell

Top 10 Contributor
Posts 555
Microsoft MVP
Top Contributor

This will read the content of all files listed in c:\file.txt. Note that the file needs to contain absolute or relative path names:

get-content c:\file.txt | Foreach-Object { Get-Content $_ }

You can also prefix folder information:

get-content c:\file.txt | Foreach-Object { Get-Content "c:\somefolder\$_" }

Then, you can collect the result and send it off as email:

$all = get-content c:\file.txt | Foreach-Object { Get-Content $_ }

Send-MailMessage -body $all ...

Use this to get familiar with Send-Mailmessage:

Help Send-MailMessage -examples

 

 

Top 500 Contributor
Posts 3

heh, yeah things do tend to break without specifying absolute paths. lol thanks for the reminder ;)

This is exactly what I was looking for though!^_^ thanks for your help Tobias!

Top 500 Contributor
Posts 3

Actually Tobias, I turns out I need a little bit of tweaking.

is it possible to echo the current line, then run the get-content $_, then echo a blank space before running through the loop again? Thanks again^_^

 

edit: nvm, I figured it out. I wasn't aware that ";" is the newline character in powershell as well. Thanks anyways though^_^

Top 10 Contributor
Posts 555
Microsoft MVP
Top Contributor

Sure. Use Write-Host for echo statements:

get-content c:\file.txt | Foreach-Object {

Write-Host $_

Get-Content $_

Write-Host '' 

}

Page 1 of 1 (5 items) | RSS
Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.