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

使用PowerCLI获取ESXi主机LUN路径时遇管道输入错误求助

问题排查与修复方案

错误根源

你传入的'gen35'是字符串类型,但Get-ScsiLun cmdlet无法直接通过管道接收字符串输入,它需要的是VMHost对象,这就是报错的核心原因。

具体修复步骤

  1. 将主机名转换为VMHost对象:在函数内部,通过Get-VMHost把字符串主机名转换成对应的VMHost对象,确保后续cmdlet能正确处理。
  2. 限定数据存储范围:原代码中$VMHostDatastores = Get-Datastore会获取所有数据存储,改为仅获取当前主机关联的数据存储,避免跨主机匹配错误。
  3. 处理路径状态的数组输出:原代码中Path State会返回数组(每个路径对应一个状态),转换为逗号分隔的字符串让报表更易读。
  4. 闭合try代码块:补充缺失的try块闭合逻辑,加入错误捕获便于排查问题。

修正后的完整代码

$vkcpw = Get-Content E:\Encrypted_Password\vkcpw.txt | ConvertTo-SecureString -Key (Get-Content E:\Encrypted_Password\V-center_aes.key)
$vcentercredential = New-Object System.Management.Automation.PsCredential("",$vkcpw)
Connect-VIServer -server 192.168.1.3 -Credential $vcentercredential

function Get-LUNPathState {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true,Position = 0,HelpMessage = 'ESXi Host',ValueFromPipeline = $true)]
        [Alias('Name')]
        [ValidateNotNullorEmpty()]
        $VMhosts
    )

    $ReportLunPathState = @()
    $i = 0

    try {
        ForEach ($VMHostName in $VMhosts) {
            $i++
            # 将字符串主机名转换为VMHost对象
            $VMHost = Get-VMHost -Name $VMHostName -ErrorAction Stop
            # 获取当前主机关联的数据存储
            $VMHostDatastores = $VMHost | Get-Datastore
            $VMHostScsiLuns = $VMHost | Get-ScsiLun -LunType disk

            ForEach ($VMHostScsiLun in $VMHostScsiLuns) {
                $VMHostScsiLunPaths = $VMHostScsiLun | Get-ScsiLunPath
                # 将路径状态数组转换为逗号分隔的字符串
                $pathStates = $VMHostScsiLunPaths.State -join ', '
                $ReportLunPathState += ($VMHostScsiLunPaths | Measure-Object) | Select-Object `
                -Property @{N = 'Hostname'; E = {$VMHost.Name}}, `
                @{N = 'Datastore'; E = {$VMHostDatastores | Where-Object {($_.extensiondata.info.vmfs.extent | ForEach-Object {$_.diskname}) -contains $VMHostScsiLun.CanonicalName} | Select-Object -ExpandProperty name}}, `
                @{N = 'CanonicalName'; E = {$VMHostScsiLun.CanonicalName}}, `
                @{N = '# of Paths'; E = {$_.Count}}, `
                @{N = 'Path State'; E = {$pathStates}}
            }
        }
        # 返回生成的报表
        return $ReportLunPathState
    }
    catch {
        Write-Error "处理主机 $VMHostName 时出错: $_"
    }
}

# 调用函数,支持传入单个或多个主机名(如@('gen35','gen36'))
Get-LUNPathState -VMhosts 'gen35'

额外说明

  • 如果需要批量处理多个主机,直接传入主机名数组即可,比如Get-LUNPathState -VMhosts @('gen35','gen36')。
  • 加入了-ErrorAction Stop和catch块,方便排查单个主机处理失败的具体问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:21:35