Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dump the foreach loop output into a file in PowerShell?

I have wrote the following script to read the CSV file to perform the custom format of output.

Script is below:

$Content = Import-Csv Alert.csv
foreach ($Data in $Content) {
    $First = $Data.DisplayName
    $Second = $Data.ComputerName
    $Third = $Data.Description
    $Four = $Data.Name
    $Five = $Data.ModifiedBy
    $Six = $Data.State
    $Seven = $Data.Sev
    $Eight = $Data.Id
    $Nine = $Data.Time

    Write-Host "START;"
    Write-Host "my_object="`'$First`'`;
    Write-Host "my_host="`'$Second`'`;
    Write-Host "my_long_msg="`'$Third`'`;
    Write-Host "my_tool_id="`'$Four`'`;
    Write-Host "my_owner="`'$Five`'`;
    Write-Host "my_parameter="`'$Four`'`;
    Write-Host "my_parameter_value="`'$Six`'`;
    Write-Host "my_tool_sev="`'$Seven`'`;
    Write-Host "my_tool_key="`'$Eight`'`;
    Write-Host "msg="`'$Four`'`;
    Write-Host "END"
}

The above script executing without any error.

Tried with Out-File and redirection operator in PowerShell to dump the output into a file, but I'm not finding any solution.

like image 312
HamTheAstroChimp Avatar asked Jun 27 '14 13:06

HamTheAstroChimp


1 Answers

Write-Host writes to the console. That output cannot be redirected unless you run the code in another process. Either remove Write-Host entirely or replace it with Write-Output, so that the messages are written to the Success output stream.

Using a foreach loop also requires additional measures, because that loop type doesn't support pipelining. Either run it in a subexpression:

(foreach ($Data in $Content) { ... }) | Out-File ...

or assign its output to a variable:

$output = foreach ($Data in $Content) { ... }
$output | Out-File ...

Another option would be replacing the foreach loop with a ForEach-Object loop, which supports pipelining:

$Content | ForEach-Object {
  $First = $_.DisplayName
  $Second = $_.ComputerName
  ...
} | Out-File ...

Don't use Out-File inside the loop, because repeatedly opening the file will perform poorly.

like image 195
Ansgar Wiechers Avatar answered Sep 19 '22 20:09

Ansgar Wiechers