有没有办法将文本表转换为 PowerShell 对象

And*_*der 5 regex powershell text-parsing

有许多工具可以以表格格式输出数据。一个这样的例子是diskpart。去掉一些无关的输出,你会得到这样的东西。

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        *
Run Code Online (Sandbox Code Playgroud)

另一个示例是 netstat,如下所示:

 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
Run Code Online (Sandbox Code Playgroud)

我想弄清楚是否有一种相当可重复的方法将这种类型的数据转换为对象,这样对象的属性就是第一行的标题。我知道有很多方法可以使用正则表达式为单个工具的输出执行此操作,但我正在寻找更多有关如何解决此问题的策略,而不是仅针对 diskpart 或 netstat 的一次性解决方案。

我试图弄清楚如何在名为Convert-TextToObject 的 Poshcode上使用 Lee Holmes 的脚本,但不太确定从哪里开始。

JPB*_*anc 0

从战略角度来看,我会尝试将您的文本文件转换为正确的 CSV(逗号分隔值)文件,然后使用Import-Csv.