【问题标题】:Can you have multiple IN conditions in a PowerShell ForEach loop?PowerShell ForEach 循环中可以有多个 IN 条件吗?
【发布时间】:2019-09-03 20:22:23
【问题描述】:

我在函数中有以下示例代码:

[array]$ARR = $null

foreach ($file in $fileTable.identical)
{
   [hashtable]$HT=@{
       'FileName' = $file.Name
       'AppName' = $file.App
       'GroupName' = $file.Group
       'Valid' = $true
   }
   $ARR += $HT
}
foreach ($file in $fileTable.removed)
{
   [hashtable]$HT=@{
       'FileName' = $file.Name
       'AppName' = $file.App
       'GroupName' = $file.Group
       'Valid' = $false
   }
   $ARR += $HT
}
foreach ($file in $fileTable.modified)
{
   [hashtable]$HT=@{
       'FileName' = $file.Name
       'AppName' = $file.App
       'GroupName' = $file.Group
       'Valid' = $false
   }
   $ARR += $HT
}

return $ARR

其他 $fileTable.[properties] 的 +3 个 foreach 循环,其中 'Valid' = $false 也是如此。

不必多次重复该代码块,我想做类似的事情:

foreach (($file in $fileTable.removed) -and ($file in $fileTable.modified))
{
   [hashtable]$HT=@{
       'FileName' = $file.Name
       'AppName' = $file.App
       'GroupName' = $file.Group
       'Valid' = $false
   }
}

所以只有哈希表中不同的变量是 $value。 $fileTable 是一个 pscustomobject,具有一些自定义属性,例如相同、修改、添加、删除。

我知道我想要的在 foreach 循环中是不可能的,但我正在寻找一种类似的解决方案来减少代码行数。任何帮助将不胜感激:)

谢谢!

【问题讨论】:

  • $ARR = @('identical', 'removed', 'modified' | % { $fileTable.$_ } | % { @{ 'FileName' = $_.Name; 'AppName' = $_.App; 'GroupName' = $_.Group; 'Valid' = $false } })

标签: powershell loops foreach hashtable


【解决方案1】:

结合您和PetSerAls 的方法。

编辑:合并@mklement0s 提示

$ARR = foreach($Variant in 'identical', 'removed', 'modified'){
  $fileTable.$Variant | ForEach-Object{
    [PSCustomObject]@{
      'FileName'  = $_.Name
      'AppName'   = $_.App
      'GroupName' = $_.Group
    # 'Valid'     = if($Variant -eq 'identical'){$True} else {$False}
      'Valid'     = $Variant -eq 'identical'
    }
  }
}

【讨论】:

  • 做得很好,但'Valid' = $Variant -eq 'identical' 应该这样做。
猜你喜欢
  • 1970-01-01
  • 2019-11-01
  • 2015-09-08
  • 2019-09-14
  • 2020-02-06
  • 2011-12-09
  • 2021-05-21
  • 1970-01-01
  • 2016-04-03
相关资源
最近更新 更多