我编写了以下脚本来读取CSV文件以执行输出的自定义格式。
脚本如下:
$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"
}
上述脚本执行时没有任何错误。
尝试使用PowerShell中的Out-File
和重定向运算符将输出转储到文件中,但我找不到任何解决方案。
答案 0 :(得分:17)
Write-Host
写入控制台。除非您在另一个进程中运行代码,否则无法重定向该输出。完全删除Write-Host
或将其替换为Write-Output
,以便将消息写入Success输出流。
使用foreach
循环还需要其他措施,因为该循环类型不支持流水线操作。在子表达式中运行它:
(foreach ($Data in $Content) { ... }) | Out-File ...
或将其输出分配给变量:
$output = foreach ($Data in $Content) { ... }
$output | Out-File ...
另一个选择是用foreach
循环替换ForEach-Object
循环,它支持流水线操作:
$Content | ForEach-Object {
$First = $_.DisplayName
$Second = $_.ComputerName
...
} | Out-File ...
不要在循环中使用Out-File
,因为重复打开文件的效果会很差。