How to dump the foreach loop output into a file in PowerShell? -
i have wrote following script read csv file perform custom format of output.
script 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 error.
tried out-file , redirects operator in powershell dump output file, i'm not finding solution.
write-host writes console. output cannot redirected unless run code in process. either remove write-host entirely or replace write-output, messages written success output stream.
using foreach loop requires additional measures, because loop type doesn't support pipelining. either run in subexpression:
(foreach ($data in $content) { ... }) | out-file ...   or assign output variable:
$output = foreach ($data in $content) { ... } $output | out-file ...   another option replacing foreach loop foreach-object loop, supports pipelining:
$content | foreach-object {   $first = $_.displayname   $second = $_.computername   ... } | out-file ...   don't use out-file inside loop, because repeatedly opening file perform poorly.
Comments
Post a Comment