powershell - foreach-object if return , 返回所有值问题

标签 powershell foreach

我生成了这个奇怪的输出。 $abc 是一个大约有 200 个节点的 xml 我尝试搜索主机名 cat01.pdx30 的特定元素,但下面似乎打印出 abc 中的所有主机名,有什么想法吗?

($abc.DeviceMetaData) | ForEach-Object { 
    if ($PSItem.Device.HostName -match  [regex]::Escape("cat01.pdx30")) {
        return $psitem.Device.HostName 
    }
}

$abc 看起来像这样:

<?xml version="1.0"?>
<DeviceMetaData xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Device HostName="cat02.pdx30">
    <Property Name="Home">Region</Property>
  </Device>
  <Device HostName="cat01.mwh01">
    <Property Name="AclFile" />
    <Property Name="AnchorPresent">False</Property>
    <Property Name="CloudType">Public</Property>
    <Property Name="ConfigTemplateFile">iper_Ce.xml</Property>
    <Property Name="DcCode">mwh01</Property>
  </Device>
  <Device HostName="ALB70-RME71-226-01OSP">
    <Property Name="OpticalEnabled">True</Property>
  </Device>
</DeviceMetaData>

最佳答案

根据数据示例,您没有指示 powershell 处理 DeviceMetaData 元素的子元素

$abc.DeviceMetaData.Device | ForEach-Object { 
    if($_.HostName -match [regex]::Escape("cat01.pdx30")) {
        $PSItem.Hostname
    }
}

上面的示例告诉 PowerShell 遍历所有 Device 元素。对于这些对象中的每个对象,它将与 HostName 属性进行匹配,如果存在匹配,则仅输出 HostName。

请考虑不要在 PowerShell 中使用 return 关键字。 return 关键字会中断当前作用域的执行,这与仅仅输出一些数据完全不同。

请注意,您的示例数据和您的搜索条件并不相同。您的数据中没有任何“cat01.pdx30”主机名。只是为了让您不会认为该解决方案不起作用。

更新 根据新的要求,此示例执行了预期的操作。

$abc.DeviceMetaData.Device | ForEach-Object {
    if($_.HostName -match [regex]::Escape("cat01.mwh01")) {
        $PSItem.Property | Where-Object Name -eq "DcCode" | Select-Object "#text"
    }
}

在新示例中,我们遍历所有 Property 元素,使用 Where-Object 过滤它们,并使用 magical "#text"指示 powershell 读取属性的值,而不是具有名称和值的属性。

关于powershell - foreach-object if return , 返回所有值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52773080/

相关文章:

php - 如何将多维数组中的大量内容存储到mysql数据库中?

powershell - 使用 Powershell 定位和更新文本文件中的键值

c# - Linq Foreach GroupBy 在哪里

mysql - 如何循环遍历特定的列名并清除 PHP/MySQL 中的这些字段?

windows - 获取ADSI对象的用户域名?

PowerShell:如果未找到字符串,则会出现不必要的错误

javascript - Angular.forEach 只返回一个结果?

powershell - 如何查询某些关键字的多个文本文件并以文本形式输出结果?

powershell - 如何获取有关 Azure VM 上 DSC 执行的反馈?

arrays - 从 Powershell 使用数组参数调用构造函数