gpt4 book ai didi

arrays - 不能将成员添加为同名成员存在

转载 作者:行者123 更新时间:2023-12-02 22:18:41 25 4
gpt4 key购买 nike

有人可以帮我获取磁盘信息吗?我有 3 个磁盘,但我无法使用 add member 获取它们的信息。

我收到一个错误:

"Add-Member : Cannot add a member with the name "Disks" because a member with that name already exists. If you want to overwrite the member anyway, use the Force parameter to overwrite it."

这是我的代码:
function  Get-Inven {

param([string[]]$computername)

#Import-Module ActiveDirectory

foreach ($computer in $computername) {
$disks = Get-WmiObject -Class Win32_LogicalDisk -ComputerName $computer -Filter 'DriveType=3'
$os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer
#$comp = Get-ADComputer -Filter { cn=$computer }

$info = @{
'ComputerName'=$computer;
'OSVersion'=$os.caption;
'DnsHostName'=$comp.dnshostname
}

$obj = New-Object -TypeName PSObject -Property $info

foreach ($disk in $disks) {
$info = @{
'DriveLetter'=$disk.deviceID;
'FreeSpace'=($disk.freespace / 1MB -as [int])
}
$diskobj = New-Object -TypeName PSObject -Property $Info
$obj | Add-Member -MemberType NoteProperty -Name Disks -Value $diskobj
}
}

}

最佳答案

如果添加 -Force 参数,您仍然可以设置 Name 属性。您还应该添加 -PassThru 开关参数以将对象发送回管道:

$obj | Add-Member -MemberType NoteProperty -Name Disks -Value $diskobj -Force -PassThru

更新:

在我看来,您可以简化函数(没有添加成员调用):
foreach ($computer in $computername) {
$disks = Get-WmiObject -Class Win32_LogicalDisk -ComputerName $computer -Filter 'DriveType=3'
$os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer
#$comp = Get-ADComputer -Filter { cn=$computer }

$info = @{
ComputerName=$computer
OSVersion=$os.caption
DnsHostName=$comp.dnshostname
FreeSpaceMB= ($disks | foreach { "{0},{1:N0}" -f $_.Caption,($_.freespace/1MB) }) -join ';'
}

New-Object -TypeName PSObject -Property $info
}

关于arrays - 不能将成员添加为同名成员存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6716169/

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