I am trying to go through a list of servers for further querying via WMI
. Unfortunately, if the scripts hits a server that cannot connect via WMI
, it takes a long time before timing out.
These are generally servers in our DMZ, and allocated a specific address in the 2nd octet of the IP address, .92
for example. So I am looking to filter out these servers as the first step in my query, so it can be ignore in any further WMI
queries.
I have found many examples on how to do this, and again, I cannot use WMI
methods as this defeats the object (eg: Get-WmiObject Win32_NetworkAdapterConfiguration
).
In the example below, the server "SERVER" has an IP of 192.9.4.1
and I want to filter out all servers with ".9" in the second octet. so I use a simple Test-Connection
cmdlet, and aim to split the result. Before I can split it, the result of the Test-Connection
is:
$IP4Address = Test-Connection _Computer SERVER -Count 1 | Select IPV4Address
@{IPV4Address=192.9.4.1}
Which means that I need to count 19 chars from the beginning to get my "9". IPV4Address
$Octet = $IP4Address -split ("")
If ($Octet[19] -eq '9')
{write-host "In DMZ"}
Else
{write-host "Not in DMZ"}
Before you ask, I did try -split (".")
but this doesn't seem to take any effect.
So why does the result come out like @{IPV4Address=192.9.4.1}
? Is there a better solution?
To only get the value of the IPV4Address
property you will have to expand it:
$IP4Address = Test-Connection -Computer SERVER -Count 1 |
Select-Object -ExpandProperty IPV4Address
Then you can use the .Split()
method:
if($IPV4Address.Split(".")[1] -eq "9") {
"In DMZ"
} else {
"Not in DMZ"
}
PS : I usually use -Count 2
rather than -Count 1