You state that your get_alerts
function uses Write-Host
to print to the screen.
Write-Host
's output by design isn't sent to PowerShell's success output stream[1], so nothing is captured in $output
, so nothing is sent to Out-File
, which is why you end up with an empty file.
If you can modify the get_alerts
function, replace Write-Host
calls with Write-Output
calls, or just use implicit output (e.g., instead of Write-Host $foo
, use Write-Output $foo
or simply $foo
).
If you cannot, and if you're using PowerShell v5 or higher, you can use redirection 6>&1
to redirect Write-Host
output to the success output stream, which allows you to capture it:
& { foreach ($elem in $ashost) { get_alerts $elem } } 6>&1 | Out-File C:\File.txt
Or, using a single pipeline:
$ashost | ForEach-Object { get_alerts $_ } 6>&1 | Out-File C:\File.txt
See this answer for more information.
[1] Write-Host
is typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, redirect it to a file. In PSv5+ Write-Host
writes to the information stream, whose output can be captured, but only via 6>
. See also: the last section of https://stackoverflow.com/a/50416448/45375