powershellpipewrite-host

Piping output from Write-Host to other command


I have this script that finds files based on certain cafeterias and write their path using Write-Host. Now, I would like to pipe all of these file paths, and do stuff with those files.

Basically the first script is like this:

FindFiles.ps1:
Write-Host "C:\SomeDir\file1.txt"
Write-Host "D:\OtherDir\file2.txt"

Now I would like to do something like this:

FindFiles.ps1 | foreach { Copy-Item $_ c:\backup\ }

but clearly that does not work. (in reality I want to do something more complicated than just copy do a folder, but that is another problem :-) )


Solution

  • Write-Host specifically only prints to the console, it does not "return" anything.

    If you change your script to just output the strings, it will work.

    From:

    Write-Host "C:\SomeDir\file1.txt"
    Write-Host "D:\OtherDir\file2.txt"
    

    To:

    "C:\SomeDir\file1.txt"
    "D:\OtherDir\file2.txt"