在Powershell中将对象添加到对象数组 [英] Add objects to an array of objects in Powershell
本文介绍了在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屋!
查看全文