我們可以將低於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」 –