【发布时间】:2018-07-08 12:05:00
【问题描述】:
我在$DSConfigPath 有一个 XML 文件,其中包含以下信息:
<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>
我的目标是对<activeStatus> 为“真”的任何 IP/端口进行端口连接测试。
我有以下函数,当我输入特定的 $hostname 和 $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
}
所以现在当我添加以下变量时:
[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
然后运行:
foreach ($DSActive in $DSConfig) {Test-Port $hostname $port}
我得到了结果:
可能 10.1.1.10 10.1.1.11 是错误的主机名或 IP有什么建议可以让我测试到 10.1.1.10:952 的连接,给出结果,然后测试到 10.1.1.11:952 的连接,然后给出结果?
【问题讨论】:
-
foreach ($DSActive in $DSConfig)没有意义 - 您刚刚在前一个块中将$DSConfig定义为[xml]文档。请发帖an mvce -
谢谢...诚然我不知道自己在做什么...这就是我来这里寻求帮助的原因...
-
如果您能确保您发布的示例 XML 确实有效(如“不缺少一对尖括号”),将会有所帮助。
标签: xml powershell foreach