我们可以将低于txt文件转换为在最后添加的CSV格式吗?需要使用PowerShell将txt文件转换为CSV(带标题)
文本文件:
IP Address: 192.168.1.1 Hostname: 01-any1TEST Event Message: Ping Alert Status: Down at 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 at 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 at least 3 min Event Time: 17:26:21 Alert Type: :windows host -------------------------------------------------------------------------------------
CSV文件输出要求如下:
'IP Address','Hostname','Event Message','Alert Status','Event Time','Alert Type' '192.168.1.1','01-any1TEST','Ping','Down at least 3 min','17:26:21','Windows 2012 Server ' '192.168.1.2','02-any2TEST','Ping','Down at least 3 min','17:26:21','unix host ' '192.168.1.3','03-any3TEST','Ping','Down at least 3 min','17:26:21','windows host '
它有可能,你有没有做过自己的尝试? – arco444
是的。 $ input = Get-Content -path“path \ Desktop \ in.txt”| Select-String -List'Alert Type','IP Address','Hostname','Event Message','Alert Status','Event Time' $ data = $ input [1 ..($ input.Length - 1 )] $ maxLength = 0 –
$ objects = ForEach($ data in $ data){ $ split = $ record -split“\ s {2,} | \ t +” If($ split.Length -gt $最大长度){$ 最大长度= $ split.Length } $道具= @ {} 对于($ I = 0; $ I -lt $ split.Length; $ I ++){$ props.Add([字符串] ($ I + 1),$分裂[$ i]于) } 新物体-TypeName PSObject -Property $道具 } $标题= [字符串[]](0 .. $最大长度) $ heade rs1 = [String []]('MachineType','EventTime','HostName','IPAddress','AlertMessage','Severity','AlertType','AlertStatus') $ objects | Select-Object $ headers | Export-Csv -NoTypeInformation -Path“path \ out.csv” –