export to csv - Need to convert txt file to CSV (with headers) using PowerShell -


can convert below txt file csv format added @ end?

text file:

 ip address: 192.168.1.1 hostname: 01-any1test  event message: ping alert status: down @ least 3 min event time: 17:25:14 alert type: :windows 2012 server ------------------------------------------------------------------------------------- ip address: 192.168.1.2 hostname: 02-any2test   event message: ping alert status: down @ least 4 min event time: 17:25:40 alert type: :unix server ------------------------------------------------------------------------------------- ip address: 192.168.1.3 hostname: 03-any3test  event message: ping alert status: down @ least 3 min event time: 17:26:21 alert type: :windows host  ------------------------------------------------------------------------------------- 

csv file output required below:

 'ip address','hostname','event message','alert status','event time','alert type' '192.168.1.1','01-any1test','ping','down @ least 3 min','17:26:21','windows 2012 server ' '192.168.1.2','02-any2test','ping','down @ least 3 min','17:26:21','unix host ' '192.168.1.3','03-any3test','ping','down @ least 3 min','17:26:21','windows host ' 

i hope solve problem:

function convert2csv() {     param($logfile, $csvfile)      "'ip address','hostname','event message','alert status','event time','alert type'" | out-file  $csvfile       get-content $logfile -delimiter "-------------------------------------------------------------------------------------" | &{ process{        $isvalidmatch=$_ -match "ip address: (.*)\r\nhostname: (.*)\r\nevent message: (.*)\r\nalert status: (.*)\r\nevent time: (.*)\r\nalert type: (.*)\r\n"        if($isvalidmatch)        {            $nextline="'$($matches[1])','$($matches[2])','$($matches[3])','$($matches[4])','$($matches[5])','$($matches[6])'" | out-file  $csvfile -append        }     }}  } 

finally call convert2csv function, , define log file , output file parameter:

convert2csv -logfile .\1.txt -csvfile 3.txt 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -