Is there a way to convert text tables to a PowerShell object

There are many tools that display their data in a table format. One such example is diskpart. Get rid of an extraneous exit, you will get something like this.

Disk ### Status Size Free Dyn Gpt -------- ------------- ------- ------- --- --- Disk 0 Online 136 GB 0 B Disk 1 Offline 136 GB 136 GB Disk 2 Reserved 1027 MB 0 B * Disk 3 Reserved 500 GB 0 B * Disk 4 Reserved 500 GB 0 B * Disk 5 Reserved 10 GB 0 B * Disk 6 Reserved 13 GB 0 B * Disk 7 Reserved 4102 MB 0 B * Disk 8 Reserved 7169 MB 0 B * Disk 9 Reserved 503 GB 0 B * Disk 10 Reserved 506 GB 0 B * Disk 11 Reserved 500 GB 0 B * Disk 12 Reserved 3891 GB 0 B * Disk 13 Reserved 500 GB 0 B * Disk 14 Reserved 3891 GB 0 B * Disk 15 Reserved 1843 GB 0 B Disk 16 Reserved 3072 GB 0 B * Disk 17 Reserved 2048 GB 0 B * Disk 18 Reserved 808 GB 0 B * Disk 19 Reserved 805 GB 0 B * Disk 20 Reserved 3891 GB 0 B * Disk 21 Reserved 3891 GB 0 B * Disk 22 Reserved 3891 GB 0 B * Disk 23 Reserved 6144 GB 0 B * 

Another example is netstat, which looks like this:

  Proto Local Address Foreign Address State TCP 0.0.0.0:80 7ANDYS:0 LISTENING TCP 0.0.0.0:135 7ANDYS:0 LISTENING TCP 0.0.0.0:443 7ANDYS:0 LISTENING TCP 0.0.0.0:445 7ANDYS:0 LISTENING TCP 0.0.0.0:1025 7ANDYS:0 LISTENING TCP 0.0.0.0:1026 7ANDYS:0 LISTENING TCP 0.0.0.0:1027 7ANDYS:0 LISTENING TCP 0.0.0.0:1028 7ANDYS:0 LISTENING TCP 0.0.0.0:1029 7ANDYS:0 LISTENING TCP 0.0.0.0:2048 7ANDYS:0 LISTENING 

I am trying to find out if there is a fairly repeatable way of converting this data type to an object, so that the properties of the object are the headers on the first line. I know that there are many ways to do this to output individual tools using regex, but I'm looking for a more strategy on how to solve this problem, rather than a one-time solution for diskpart or netstat only.

I tried to figure out how to use the โ€œLyon Holmesโ€ script on a Poshcode called Convert-TextToObject , but itโ€™s not necessarily where to start.

+4
source share
4 answers

From a strategic point of view, I will try to convert your text file to the correct CSV (data separated by coma), and then use Import-Csv .

0
source

I did it yesterday :). You can use out-datatable to convert your data to System.DataTable . Get it poshcode .

See my recent post for more details.

0
source

Something for the netstat example:

 get-content netstat.txt | select -skip 1 | ConvertFrom-String -propertynames blank,proto,local,foreign,state | select * -ExcludeProperty blank proto local foreign state ----- ----- ------- ----- TCP 0.0.0.0:80 7ANDYS:0 LISTENING TCP 0.0.0.0:135 7ANDYS:0 LISTENING TCP 0.0.0.0:443 7ANDYS:0 LISTENING 
0
source

All Articles