gpt4 book ai didi

powershell - 使用Add-Member从数组创建对象

转载 作者:行者123 更新时间:2023-12-03 00:14:28 26 4
gpt4 key购买 nike

我正在使用脚本来创建具有以下特定值的新对象。这在$ Names返回单个字符串值的情况下起作用,但是当存在数组时并且在打印$ newobj之前,将得到以下错误。当我为$ Names添加foreach语句时,试图找出导致错误的原因。还要注意,对于$ names数组中的两个值John,Jake,$ x的值与“London”相同。

在当前输出中,StudentName两次都打印为“John”,当我使用参数–Force时,StudentName的值两次都为“Jake”。我需要在输出中将这些值分开,有人可以帮助我吗?请?

Add-Member : Cannot add a member with the name "StudentName" because a member with that name already exists. To overwrite the
member anyway, add the Force parameter to your command.
At E:\test.ps1:93 char:14
+ $newobj | Add-Member -MemberType NoteProperty -Name StudentName -Value $_

脚本:
# $DCNames is an array

Foreach($x in $DCNames){
$newobj = New-Object psobject
$newobj | Add-Member -MemberType NoteProperty -Name DC -Value $x

###### $Names in most cases is a single string or it could be also an array. For example: it could be a value Adam or {John Jake….} and so I would need to Add each member in $Names as StudentName object below.
$Names =@()
$Names = $List | Where-Object{$_.Name -eq $x} | Select -ExpandProperty Name

$Names | foreach {
$newobj | Add-Member -MemberType NoteProperty -Name StudentName -Value $_
# $ClassName is a single string
$newobj | Add-Member -MemberType NoteProperty -Name Class -Value $ClassName
$newobj
}

电流输出:
Name: Vegas
StudentName: Adam
Class: 10

Name: London
StudentName: John
Class: 12

Name: London
StudentName: John (the script should take the second value “Jake” here from $Names array, but is not happening for some reason)
Class: 11

最佳答案

您仅创建1个对象,然后尝试覆盖同一对象上的StudentName。改为这样做:

Foreach($x in $DCNames){
###### $Names in most cases is a single string or it could be also an array. For example: it could be a value Adam or {John Jake….} and so I would need to Add each member in $Names as StudentName object below.
$Names = @()
$Names = $List | Where-Object{$_.Name -eq $x} | Select -ExpandProperty Name

$Names | foreach {
$newobj = New-Object psobject
$newobj | Add-Member -MemberType NoteProperty -Name DC -Value $x
$newobj | Add-Member -MemberType NoteProperty -Name StudentName -Value $_
$newobj | Add-Member -MemberType NoteProperty -Name Class -Value $ClassName
$newobj
}
}

用管道传输到 Add-Member可能会很慢,您可能想改用 New-Object -Property @{}:
Foreach($x in $DCNames){
###### $Names in most cases is a single string or it could be also an array. For example: it could be a value Adam or {John Jake….} and so I would need to Add each member in $Names as StudentName object below.
$Names = @()
$Names = $List | Where-Object{$_.Name -eq $x} | Select -ExpandProperty Name

$Names | foreach {
$newobj = New-Object psobject -Property @{
DC = $x
StudentName = $_
Class = $ClassName
}
}
}

关于powershell - 使用Add-Member从数组创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39241913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com