A PowerShell script is failing on certain servers. PowerShell version on the server where it fails is 2.
Here is the code:
(Get-WmiObject Win32_NetworkAdapterConfiguration -Filter "ipenabled = 'True'").IPAddress[0]
On the server where it works, the output is the IP address of the server. As an example:
10.1.1.1
On the server where it fails, here is the output:
Cannot index into a null array. At line:1 char:90
+ (Get-WmiObject Win32_NetworkAdapterConfiguration -Filter "ipenabled = 'True'").IPAddress[ <<<< 0]
+ CategoryInfo : InvalidOperation: (0:Int32) [], RuntimeException
A major difference between the servers are:
- Where it works (as per my observations); there is a single IP address (Single NIC).
- On the server where it fails, there are multple NICs with different subnets (so one IP will be 10.x.x.x and second will be 172.x.x.x) -- I would want the script to pick up IP starting 10.x.x.x.
Here is the output if I remove .IPAddress[0]:
Script:
(Get-WmiObject Win32_NetworkAdapterConfiguration -Filter "ipenabled = 'True'")
Output on working server:
DHCPEnabled : False
IPAddress : {10.x.x.x}
DefaultIPGateway : {10.x.x.x}
DNSDomain :
ServiceName : NIC
Description : NIC NAME
Index : 11
Output on servers where the script fails:
DHCPEnabled : False
IPAddress : {172.x.x.x}
DefaultIPGateway :
DNSDomain :
ServiceName : l2nd
Description : NIC #34
Index : 13
DHCPEnabled : False
IPAddress : {10.x.x.x}
DefaultIPGateway : {10.x.x.x}
DNSDomain :
ServiceName : iANSMiniport
Description :
Index : 20
IPAddressproperty, and member enumeration was "invented" in PowerShell v3, so it will not work in v2. - user4003407Get-WmiObject ... | Select-Object -First 1 -Expand IPAddress- Ansgar Wiechers