PowerShell 中的陣列是什麼?
陣列由一組相同資料型別或不同資料型別的元素組成。當輸出包含多行時,輸出或儲存的變數會自動變成陣列。其資料型別為 **Object[] 或 ArrayList**,基本型別為 **System.array** 或 **System.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
您可以使用 **Select-String** 管道命令過濾整個輸出以查詢特定單詞,以便顯示包含該單詞的行。
例如,要檢查系統中可用的乙太網介面卡。
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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP