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

白昼怎懂夜的黑 提交于 2019-11-30 09:17:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/24453370/how-to-dump-the-foreach-loop-output-into-a-file-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!