如何将 foreach 循环输出转储到 PowerShell 中的文件中? [英] How to dump the foreach loop output into a file in PowerShell?
问题描述
我编写了以下脚本来读取 CSV 文件以执行自定义格式的输出.
I have wrote the following script to read the CSV file to perform the custom format of output.
脚本如下:
$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.
在 PowerShell 中尝试使用 Out-File
和重定向运算符将输出转储到文件中,但我没有找到任何解决方案.
Tried with Out-File
and redirection operator in PowerShell to dump the output into a file, but I'm not finding any solution.
推荐答案
Write-Host
写入控制台.除非您在另一个进程中运行代码,否则无法重定向该输出.完全删除 Write-Host
或将其替换为 Write-Output
,以便将消息写入 Success 输出流.
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.
使用 foreach
循环还需要额外的措施,因为该循环类型不支持流水线.要么在子表达式中运行它:
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 ...
另一种选择是用支持流水线的 ForEach-Object
循环替换 foreach
循环:
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 ...
不要在循环内使用Out-File
,因为重复打开文件会性能不佳.
Don't use Out-File
inside the loop, because repeatedly opening the file will perform poorly.
这篇关于如何将 foreach 循环输出转储到 PowerShell 中的文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!