代码之家  ›  专栏  ›  技术社区  ›  wetin

使用两个等长数组执行数学运算

  •  0
  • wetin  · 技术社区  · 5 年前

    我所做的是如此简单,以至于我在努力寻找答案。我想把两个等长的数组相减

    $free_array = get-wmiobject -class win32_logicaldisk | select -ExpandProperty freespace
    $size_array = get-wmiobject -class win32_logicaldisk | select -ExpandProperty size
    
    ForEach ($size in $size_array)
      {
        Write-Host Statistic: $size - $freespace
      }
    
    
    1 回复  |  直到 5 年前
        1
  •  5
  •   Don Cruickshank    5 年前

    我不认为PowerShell有一个内置函数可以同时映射到多个数组,因此您可以使用 range operator 然后根据需要索引到两个数组中:

    foreach ($Index in (0..($free_array.Count - 1))) {
        Write-Host Statistic: ($size_array[$Index] - $free_array[$Index])
    }
    

    不过,你的任务也可以这样做,我认为这样更具可读性:

    $LogicalDisks = Get-CimInstance -ClassName Win32_LogicalDisk
    
    foreach ($LogicalDisk in $LogicalDisks) {
        Write-Host Statistic: ($LogicalDisk.Size - $LogicalDisk.FreeSpace)
    }
    
        2
  •  1
  •   mklement0    5 年前

    Don Cruickshank's helpful answer :

    旁白:下面我用 Get-CimInstance Get-WmiObject ,因为CIM cmdlet(例如。, )取代了WMI cmdlet(例如。, 获取WmiObject )在PowerShell v3中(2012年9月发布)。因此,应该避免使用WMI cmdlet,尤其是因为PowerShell(Core)7+(将来所有的工作都将在这里进行)甚至不起作用 不再是他们了。有关详细信息,请参阅 this answer .

    如果你能做手术 单一的 foreach 循环,可以使用单个管道调用 ForEach-Object

    Get-CimInstance win32_logicaldisk | ForEach-Object {
      "Statistic: " + ($_.Size - $_.FreeSpace)
    }
    

    至于 倍数 并行集合

    [Linq.Enumerable]::Zip() 你能帮我吗 收藏:

    # Two sample arrays to enumerate in parallel:
    [string[]] $a1 = 'one', 'two', 'three'
    [int[]] $a2 = 1, 2, 3
    
    foreach ($tuple in [Linq.Enumerable]::Zip($a1, $a2)) {
      '{0}: {1}' -f $tuple[0], $tuple[1]
    }
    

    注意:在早期的PowerShell(Core)版本和Windows PowerShell中,您必须使用 .Item1 / .Item2 [0] / [1]

    然而,如上所示,这是 ,因为PowerShell不支持 .NET扩展方法

    GitHub proposal #14732 建议引入一个PowerShell惯用特性,该特性不仅支持 2 :

    # Two sample arrays to enumerate in parallel:
    $a1 = 'one', 'two', 'three'
    $a2 = 1, 2, 3
    
    # WISHFUL THINKING, as of PowerShell 7.2
    foreach ($a1Element, $a2Element in $a1, $a2) {
      '{0}: {1}' -f $a1Element, $a2Element
    }
    
    

    如果实现了此功能,则会输出:

    one: 1
    two: 2
    three: 3
    
    推荐文章