在PowerShell中什么是数组?

数组由一组具有相同数据类型或不同数据类型的元素组成。当输出包含多行时,输出或存储的变量将自动成为数组。其数据类型为Object []或ArrayList,基本类型为System.arraySystem.Object。

例如,

IPConfig的输出是一个数组。

示例

PS C:\WINDOWS\system32> ipconfig
Windows IP Configuration
Ethernet adapter Ethernet:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Ethernet adapter VirtualBox Host-Only Network:
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : fe80::187b:7258:891b:2ba7%19
IPv4 Address. . . . . . . . . . . : 192.168.56.1
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . :
Wireless LAN adapter Local Area Connection* 3:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Wireless LAN adapter Local Area Connection* 5:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :

如果将Ipconfig存储在变量中并检查其数据类型,则它将为Object []

PS C:\WINDOWS\system32> $ip = ipconfig
PS C:\WINDOWS\system32> $ip.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array

同样,如果您获取任何多行输出,则只能是数组。您可以使用比较方法检查变量是否为数组,如下所示。

$a = "Hello"
$a -is [Array]

输出结果

False


$ip = ipconfig
$ip -is [Array]

输出结果

True

数组索引从0开始。例如,第一行被视为0索引,第二行被视为1,以此类推。但是并非一直如此。当输出显示为多组时,则将第一组输出视为索引值0,将第二组输出视为索引值1。

您可以如下获得ipconfig输出的第二行。

$ip = ipconfig
$ip[0]

输出结果

Windows IP Configuration

您可以过滤特定单词的整个输出,以便使用“选择字符串管道”命令显示包含该单词的行。

例如,检查系统中可用的以太网适配器。

ipconfig | Select-String -pattern "Adapter"

输出结果

Ethernet adapter Ethernet:
Ethernet adapter VirtualBox Host-Only Network:
Wireless LAN adapter Local Area Connection* 3:
Wireless LAN adapter Local Area Connection* 5:
Ethernet adapter Ethernet 3:
Ethernet adapter Ethernet 4:
Wireless LAN adapter Wi-Fi:
Ethernet adapter Bluetooth Network Connection:

同样,您可以过滤IPv4地址。

ipconfig | Select-String -pattern "IPv4 Address"

输出结果

IPv4 Address. . . . . . . . . . . : 192.168.56.1
IPv4 Address. . . . . . . . . . . : 192.168.0.104