Skip to main content
 首页 » 编程设计

powershell之通过数组枚举失败

2025年01月19日17youxin

我正在枚举 VMware 环境中的所有数据存储以获取名称和已用空间。

当我运行 foreach 循环时,它既枚举数组,又不枚举数组。

这是我的脚本:

$list = @() 
$row = '' | select Name, UsedSpace 
$datastores = Get-Datastore 
 
foreach ($store in $datastores) { 
    $row.name = $store.name; 
    $row.usedspace = [math]::Round(($store.extensiondata.summary.capacity - $store.extensiondata.summary.freespace)/1gb) 
    Write-Host $row; #To Verify that each row is different, and that enumeration is working# 
    $list += $row; 
} 

控制台输出:

@{name=datastore1; usedspace=929} 
@{name=datastore2; usedspace=300} 
@{name=datastore3; usedspace=400} 

$list变量输出:

Name        Usedspace 
Datastore3  400 
Datastore3  400 
Datastore3  400 

所以它正在枚举。获取所有正确的数据。但由于某种原因,行 $list += $row 正在等待,直到数组中的最后一个对象,仅获取该数据,但知道数组中有 3 个对象,并用该数据填充每个索引对象数据。

我所做的唯一的故障排除就是退回我的 PowerShell 控制台。

请您参考如下方法:

原因是 $row 是单个对象。您创建它一次,然后不断更改其属性的值。当您将其添加到数组时,您将添加一个引用,而不是副本。因此看到的值将始终是最近设置的值。

在循环的每次迭代中重新创建 $row