Write-Host only displays output onscreen. It does not send anything down the pipeline, so you can’t redirect its output since there is nothing to redirect.
Let me ask you something? Do you actually sit in front of your computer and watch your scripts doing their work? If the answer is “no” you don’t need Write-Host regularly in your scripts anymore.
Instead you can use Write-Debug or Write-Verbose if you like to know what your scripts are doing during the process of developing. Or you simply use something like this "Log message" | Out-File -FilePath $Path if you like to log something to a file.
@Olaf, I used “Log message” instead of write-host.
and did this way:
Test_log 2>&1 4>&1 6>&1|Out-File C:\temp\log.txt
I was able to get the log messages in the log file, however, now I am not able to view it on console
with just calling function, I am able to see “Log message” and also the verbose messages which are contained in the function, but when I redirect them, won’t they be shown again on the console?
Stop watching your scripts on the console! … I think the issue is not technical it is logical. Either you want to have scripts usually running unattended in the background wíthout user intaction or you run them manually in the console. For the first one you do not need any console output. For the latter one you do.
If you want to debug scripts where you implemented extended logging you should watch the log files if you want to know what’s going on.
If you don’t want to re-invent the wheel - there are frameworks out there offering extended logging and very flexible functionalities. You may use one of them.