You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向数组追加元素时出现“Cannot index into a null array”错误求助

问题原因与解决方法

错误根源

你遇到的"Cannot index into a null array"错误,不是因为$AllObjects是null——你已经正确初始化了空数组$AllObjects = @()。问题出在代码的管道逻辑上:
你把创建的自定义对象直接管道传给Export-Csv,而Export-Csv执行后不会返回任何输出(它只负责写入文件),所以$AllObjects +=后面接的是$null。当PowerShell尝试把$null追加到数组时,就会抛出这个错误。

另外还有两个优化点:

  • 不需要每次循环都调用Get-VM -Name $vm,$vm本身就是Get-VM返回的对象,直接访问属性即可,避免重复调用浪费资源。
  • Name字段直接赋值$vm的话,CSV里会显示对象类型(比如VMware.VimAutomation.ViCore.Impl.V1.VM.VirtualMachineImpl),应该用$vm.Name获取虚拟机名称。

解决方案

方案1:保留数组同时导出CSV

如果你需要后续继续使用$AllObjects数组中的数据,可以先创建对象并添加到数组,再单独导出到CSV:

function execute_file {
    $file_output = Read-Host "Enter the .CSV local location where you would like to save resultant output.  For example, 'G:\documents\output.csv'"
    $vm_list = Get-VM | Sort-Object Name
    $AllObjects = @()

    foreach ($vm in $vm_list) {
        Write-Progress -Activity "Processing $($vm.Name) ..."
        # 创建虚拟机对象
        $vmObject = [pscustomobject]@{
            Name                     = $vm.Name
            "IP Address"             = $vm.Guest.IPAddress[0]
            "Guest OS"               = $vm.Guest.OSFullName
            PowerState               = $vm.PowerState
        }
        # 添加到数组
        $AllObjects += $vmObject
        # 导出到CSV
        $vmObject | Export-Csv -Path $file_output -Append -NoTypeInformation
    }
    # 后续可使用$AllObjects进行其他操作
}

方案2:直接导出CSV(无需数组)

如果不需要保留数组,直接通过管道一次性导出更高效,避免手动管理数组和多次追加CSV的开销:

function execute_file {
    $file_output = Read-Host "Enter the .CSV local location where you would like to save resultant output.  For example, 'G:\documents\output.csv'"
    Get-VM | Sort-Object Name | ForEach-Object {
        Write-Progress -Activity "Processing $($_.Name) ..."
        [pscustomobject]@{
            Name                     = $_.Name
            "IP Address"             = $_.Guest.IPAddress[0]
            "Guest OS"               = $_.Guest.OSFullName
            PowerState               = $_.PowerState
        }
    } | Export-Csv -Path $file_output -NoTypeInformation
}

内容的提问来源于stack exchange,提问作者cuddlydingo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:15:38