I have an XML file at $DSConfigPath
that contains information as such:
<dataSources>
<add id="DataSource1" type="Fixed" distance="1">
<parameters>
<name />
<address>10.1.1.10</address>
<otherIdentifiers>DataSource1</otherIdentifiers>
<activeStatus>true</activeStatus>
<ip>10.1.1.10</ip>
<port>952</port>
</parameters>
</add>
<add id="DataSource2" type="Fixed" distance="2">
<parameters>
<name />
<address>10.1.1.11</address>
<otherIdentifiers>DataSource2</otherIdentifiers>
<activeStatus>true</activeStatus>
<ip>10.1.1.11</ip>
<port>952</port>
</parameters>
</add>
<add id="DataSource3" type="Fixed" distance="3">
<parameters>
<name />
<address>10.1.1.12</address>
<otherIdentifiers>DataSource1</otherIdentifiers>
<activeStatus>false</activeStatus>
<ip>10.1.1.12</ip>
<port>952</port>
</parameters>
</add>
</dataSources>
My goal is to do a do a port connection test to any IP/port where the <activeStatus>
is 'true.'
I've got the following function, which I've verified will give me the correct results when I put in a specific $hostname
and $port
:
function Test-Port($hostname, $port) {
# This works no matter in which form we get $host - hostname or ip address
try {
$ip = [System.Net.Dns]::GetHostAddresses($hostname) |
Select-Object IPAddressToString -ExpandProperty IPAddressToString
if ($ip.GetType().Name -eq "Object[]") {
#If we have several ip's for that address, let's take first one
$ip = $ip[0]
}
} catch {
Write-Host "Possibly $hostname is wrong hostname or IP"
return
}
$t = New-Object Net.Sockets.TcpClient
# We use Try\Catch to remove exception info from console if we can't connect
try {
$t.Connect($ip,$port)
} catch {}
if ($t.Connected) {
$t.Close()
$msg = "Port $port is operational"
} else {
$msg = "Port $port on $ip is closed, "
$msg += "You may need to contact your IT team to open it. "
}
Write-Host $msg
}
So now when I add the following variables:
[xml]$DSConfig = gc "$DSConfigPath"
$DS = $dsconfig.datasources.add.parameters
$DSName = $DS.otherIdentifiers
$DSIP = $DS.ip
$DSPort = $DS.port
$DSActive = $DS | Where-Object {$_.activeStatus -eq 'True'}
$hostname = $DSIP # yes I realize this is redundant
$port = $DSPORT # and yes, I realize this is redundant as well
Then run:
foreach ($DSActive in $DSConfig) {Test-Port $hostname $port}
I get the result:
Possibly 10.1.1.10 10.1.1.11is wrong hostname or IP
Any suggestion how I can get it to test the connection to 10.1.1.10:952, give that result, then test the connection to 10.1.1.11:952 and then give that result?