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

后端 未结 1 919
名媛妹妹
名媛妹妹 2020-12-20 19:27

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
forea         


        
相关标签:
1条回答
  • 2020-12-20 20:27

    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.

    0 讨论(0)
提交回复
热议问题