New-Object add-member - 无法添加成员 - powershell

时间:2017-11-12 12:11:45

标签: powershell psobject

我有一个问题:( 当我添加具有与之前的Object相同的属性名称的New对象时,我有很多错误。

  

" Add-Member:无法添加名称为" ServerName"的成员因为a   具有该名称的成员已存在。无论如何要覆盖会员,   将Force par ameter添加到您的命令中。"

它有效,但有错误;) 有人给我一个解决方案??

以下示例代码:

$OutputObj = @()

$OutputObj += New-Object -TypeName PSobject
$OutputObj | Add-Member -MemberType NoteProperty -Name ServerName -Value "server1"
$OutputObj | Add-Member -MemberType NoteProperty -Name Status -Value "online"
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "01:20"

$OutputObj += New-Object -TypeName PSobject
$OutputObj | Add-Member -MemberType NoteProperty -Name ServerName -Value "server2"
$OutputObj | Add-Member -MemberType NoteProperty -Name Status -Value "online"
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "01340"

1 个答案:

答案 0 :(得分:4)

您要在阵列上添加成员,而不是在对象上添加成员。请尝试以下方法:

$OutputObj = @()

$NewObj = New-Object -TypeName PSobject
$NewObj | Add-Member -MemberType NoteProperty -Name ServerName -Value "server1"
$NewObj | Add-Member -MemberType NoteProperty -Name Status -Value "online"
$NewObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "01:20"

$OutputObj += $NewObj

$NewObj = New-Object -TypeName PSobject
$NewObj | Add-Member -MemberType NoteProperty -Name ServerName -Value "server2"
$NewObj | Add-Member -MemberType NoteProperty -Name Status -Value "online"
$NewObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "01340"
$OutputObj += $NewObj

Alernatively,我会做以下事情:

$OutputObj = @()
$OutputObj += New-Object -TypeName PSobject -Property @{
    ServerName = "server1"
    Status = "Online"
    Uptime = "01:20"
}


$OutputObj += New-Object -TypeName PSobject -Property @{
    ServerName = "server2"
    Status = "Online"
    Uptime = "01340"
}

由于Add-Member每次使用时都会销毁并生成一个新对象。