I have a text file in this format:
ServerName:srvrX1
IP:
Location:NY
OS:
ServerName:srvrX2
IP:
Location:NY
OS:Windows Server 2012
XYZ:
ServerName:srvrX3
IP:
Location:STK
OS: Win2k3
ServerName:srvrX4
IP:
Location:STK
OS:Win2k8
ServerName:srvrX5
IP:
Location:STK
OS: RedHat Linux 5
ServerName:srvrX6
IP:
Location:TKY
OS: Windows Server 2012
The number of fields could vary for each server and the number of empty lines between each server info is randm . I want the output in tabular format(ServerName and Location columns only). I am new to powershell could someone please help.
Thanks a lot. Nel
Heres a quick and dirty way to get the job done. No doubt some will come up with a more elegant solution
$matches = Select-String -Path data.txt -Pattern "^ServerName|Location"
for ($i = 0; $i -lt $matches.Count; $i += 2){
$props = [ordered]@{
ServerName = ($matches[$i].Line -split “:”)[-1]
Location = ($matches[$i+1].Line -split “:”)[-1]
}
New-Object -TypeName PSObject -Property $props
}
Use select-string to read the file. The Pattern means any line starting with ServerName or Location. You should get two lines per server
Iterate through the matches in twos
split the first line to get the server name & the second for the location
create a hash table of the properties and output via New-Object
you should get something like this
ServerName Location
srvrX1 NY
srvrX2 NY
srvrX3 STK
srvrX4 STK
srvrX5 STK
srvrX6 TKY