0

I would like to ask you pretty easy question about foreach and output,

I noticed that while we are trying to run foreach and then export it by out-file it is more complicated, my question is what is the right way to export the content with foreach ?

For instance I prepare this:

Get-Content C:\Windows.old\1.txt
$output = 
Foreach ($line in $file)

{

$line + " "+ $line.Length + " is the lengh of you user name" 
}

And I know that is incorrect, I am looking for good explanation

Yannick Meeus
  • 5,643
  • 1
  • 35
  • 34
Merop4
  • 11
  • 4

1 Answers1

0

Why is it more complicated? I would use the Foreach-Object cmdlet (but you can also go with the loop) and pipe the result to the Set-Content cmdlet (but you can also go with Out-File:

$filePath = 'C:\Windows.old\1.txt'

$content = Get-Content $filePath
$content | ForEach-Object {
     "$_ $($_.Length) is the lengh of you user name" 
} | Set-Content $filePath

Note: You may need to set the encoding.

Edit: Without changing the script:

Get-Content C:\Windows.old\1.txt
$output = Foreach ($line in $file)
{
   $line + " "+ $line.Length + " is the lengh of you user name" 
} 
$output| Out-File 'your-new-filepath.txt'
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • For you is not complicated... :D, you definitely changed the script, what about not changing the script and leave it as it, is it possible to out-file ? BTW, you replaced the existing one. – Merop4 Feb 07 '17 at 07:23
  • Thought you want to replace the exisiting one. I edited my answer and added an example without changing the script but using the out-file cmdlet. – Martin Brandl Feb 07 '17 at 07:27
  • Hi, it doesn't work because of | (pipeline) – Merop4 Feb 07 '17 at 07:57
  • Where is it?, I can't find it, I am a new player here so can you add a comment with the changes? – Merop4 Feb 07 '17 at 09:54
  • Hi,I have tan this and it works: Get-Content C:\Windows.old\1.txt $output = Foreach ($line in $file) { $line + " "+ $line.Length + " is the lengh of you user name" } $output | out-file 'C:\Windows.old\4.txt' – Merop4 Feb 07 '17 at 13:33