none
Pipe in a Foreach loop RRS feed

  • Question

  • PowerShell ISE

    Foreach ($Item in $Dir) {Write-Host $Item.Name | Out-File -FilePath $File}

    Hello,

    Could you understand this, because it doesn't work. What would be the right syntax please. Thanks

    Tuesday, May 28, 2019 5:43 PM

All replies

  • All right! I figured the way. I just had to omit "Write-Host" in the statement block thus making it :

    Foreach ($Item in $Dir) {$Item.Name | Out-File -FilePath $File} thanks

    Thursday, May 30, 2019 3:14 PM
  • Yes, write-host writes to the screen, while write-output or just the variable name can be piped.  I think you want to append the file.

    Foreach ($Item in $Dir) {$Item.Name | Out-File -FilePath $File -Append}

    I suggest doing it this way, so you can pipe from the loop, and not deal with the encoding problems out-file has (defaulting to unicode, and not checking the encoding signature before appending).  

    $Item | Foreach-Object { $_.Name } | Set-Content -Path $File

    • Edited by JS2010 Friday, May 31, 2019 2:21 PM
    Friday, May 31, 2019 2:05 PM