【问题标题】:values from a foreach loop in a function into an array将函数中的 foreach 循环中的值放入数组中
【发布时间】:2019-08-24 18:29:35
【问题描述】:

我有一个在 SCCM 任务序列中替换 PackageID 的函数,我想将所有这些包 ID 捕获到一个变量中,这样我就能够基于它创建一个报告。

问题是我已经有一个 foreach 循环在做这项工作,我不知道如何不覆盖这些值。

$Driver.PackageID 来自基于$Driversforeach 循环,其中包含

如果我运行代码,我会得到这个,因为我已经定义了 Write-Output

更新代码:

function Set-Drivers{

    foreach ($Driver in $Drivers) {

    Write-Output "Driver Name: $($Driver.Name)"
    Write-Output "DriverPackageID: $($Driver.PackageID)"
    }
}


$array = @()
$array = Set-Drivers
$hash = [ordered]@{

'DriverName'           = $Driver.Name
'DriverID'           = $Driver.PackageID
}

$array += New-Object -Typename PSObject -Property $hash

谁能解释一下,为什么我的$array 只得到第一个结果?如果我在调试模式下运行它,我可以看到值被覆盖。

【问题讨论】:

  • 您在每个循环中都将数组设置为空白。 [grin] 这个$global:array = @() 需要在你的foreach之外
  • 李说的。此外,不要在函数中修改全局变量或在循环中追加到数组。您要做的只是在循环中输出对象(将您的状态输出写入主机或详细流而不是默认流),然后在全局范围内运行$array = Set-Drivers
  • 仍然只得到一个结果,您有什么建议吗?
  • @BenDK - please 发布您的 当前 代码,因为您的评论没有告诉我们任何可能发生的事情出错了... [咧嘴笑]
  • @Lee_Dailey 用新代码更新了主帖

标签: arrays powershell foreach


【解决方案1】:

您的代码不是迭代结果,而是只使用其中一个。这是你想要的。

$array = $drivers | foreach { 
  [ordered]@{
    DriverName = $_.Name
    DriverID   = $_.PackageID
  }
}

【讨论】:

    【解决方案2】:

    您的函数不返回任何内容。它只向控制台写入行。然后在函数完成后,创建一个对象并将其添加到数组中。

    试试类似的东西

    function Set-Drivers{
        $result = foreach ($Driver in $Drivers) {
            [PsCustomObject]@{
                'DriverName'  = $Driver.Name
                'DriverID'    = $Driver.PackageID
            }
        }
        # output the result 
        # the comma wraps the result in a single element array, even if it has only one element.
        # PowerShell 'flattens' that upon return from the function, leaving the actual resulting array.
       ,$result
    }
    
    $array = Set-Drivers
    
    # show what you've got
    $array
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 2014-05-15
      • 1970-01-01
      • 2022-09-27
      相关资源
      最近更新 更多