Powershell:将对象添加到对象数组 [英] Powershell: Add objects to an array of objects

查看:84
本文介绍了Powershell:将对象添加到对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本,我想在每个 foreach 中向名为 $Target 的数组添加一个对象.

I have this script where I want to add an object to an array called $Target in every foreach.

foreach ($Machine in $Machines)
{
  $TargetProperties = @{Name=$Machine}  
  $TargetObject = New-Object PSObject –Property $TargetProperties
  $Target= @()
  $Target =  $TargetObject
}

我知道它不起作用,因为 $Target = $TargetObject 使它等于同一个对象.

I know it is not working because $Target = $TargetObject makes it equal to the same object.

如何附加到数组而不是替换?

How can I append to the array instead of replace?

推荐答案

要追加到数组,只需使用 += 运算符.

To append to an array, just use the += operator.

$Target += $TargetObject

此外,您需要在循环之前声明 $Target = @() 否则,它会在每个循环中清空数组.

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

这篇关于Powershell:将对象添加到对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆