gpt4 book ai didi

powershell - 新对象添加成员 - 无法添加成员 - powershell

转载 作者:行者123 更新时间:2023-12-02 23:09:29 25 4
gpt4 key购买 nike

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

"Add-Member : Cannot add a member with the name "ServerName" because a member with that name already exists. To overwrite the member anyway, add the Force par ameter to your command."

它可以工作但有错误;)有人为我提供解决方案吗??

示例代码如下:

$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"

最佳答案

您是在数组而不是对象上添加成员。尝试以下操作:

$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

或者,我会执行以下操作:

$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 都会销毁并生成一个新对象。

关于powershell - 新对象添加成员 - 无法添加成员 - powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47248619/

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