What is Array in PowerShell?


An array is consists of a set of elements of the same data types or the different data types. When the output consists of more than one line then output or stored variable automatically becomes the Array. Its data type is Object[] or ArrayList and base type would be System.array or System.Object.

For example,

The output of IPConfig is an array.

Example

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 . :

If you store Ipconfig in a variable and check its datatype then it would be Object[].

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

Similarly, if you take any multiline output, it would be array only. You can check if the variable is an array or not with the comparison method as shown below.

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

Output

False


$ip = ipconfig
$ip -is [Array]

Output

True

The array index starts from 0. For example, the first line is considered 0 Index, the second is 1 and so on most of the time. But it is not the case all the time. When the output is displayed as multiple sets then the first set of output is considered as index value 0, the second set is considered as the index value 1.

You can get the second line of the ipconfig output as below.

$ip = ipconfig
$ip[0]

Output

Windows IP Configuration

You can filter the entire output for the specific word so the lines containing that word would be displayed with the Select-String Pipeline command.

For example, to check the available Ethernet adapters in the system.

ipconfig | Select-String -pattern "Adapter"

Output

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:

Similarly, you can filter the IPv4 address.

ipconfig | Select-String -pattern "IPv4 Address"

Output

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

Updated on: 14-Feb-2020

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements