gpt4 book ai didi

xml - 使用PowerShell在XML文件中进行ForEach

转载 作者:行者123 更新时间:2023-12-02 23:09:14 25 4
gpt4 key购买 nike

我在$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>为“true”的任何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的连接,然后给出结果吗?

最佳答案

使用SelectNodes()从xml文档中获取<parameters>节点:

# Read XML document
[xml]$DSConfig = gc "$DSConfigPath"

# Select <parameters> nodes
$ParametersNode = $DSConfig.SelectNodes('//parameters')

# Loop over selected nodes
foreach($Node in $ParametersNode){
# Test if activeStatus == 'true'
if($Node.activeStatus -eq 'true') {
# Run the Test-Port command
Test-Port $Node.ip -port $Node.port
}
}

关于xml - 使用PowerShell在XML文件中进行ForEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com