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

Windows10下PowerShell调用Invoke-sshCommand无法存结果到变量求解决

解决建议
  • 先确认并更新Posh-SSH模块,旧版本可能存在返回结构异常的问题:

    Update-Module -Name Posh-SSH
    Import-Module Posh-SSH -Force
    
  • 使用会话ID而非IP地址调用命令,避免多会话匹配问题,同时用Here-String清晰定义多命令,添加错误捕获:

    # 定义完整命令序列,注意最后添加end退出配置模式
    $fortiCommand = @"
    config system console
    set output standard
    end
    config system dhcp server
    show
    end
    "@
    
    # 获取有效会话ID
    $sessionId = (Get-SshSession -ComputerName "192.168.38.1").SessionId
    # 执行命令并捕获结果
    $dhcpResult = Invoke-SshCommand -SessionId $sessionId -Command $fortiCommand -ErrorAction Stop
    
    # 查看结果对象的完整结构,确认输出字段
    $dhcpResult | Get-Member
    
    # 提取输出,若为数组则合并为字符串
    $dhcpOutput = $dhcpResult.Output -join "`n"
    
  • 拆分命令分步执行,确保Fortigate CLI正确处理每一步操作:

    $sessionId = (Get-SshSession -ComputerName "192.168.38.1").SessionId
    # 先设置控制台输出格式
    Invoke-SshCommand -SessionId $sessionId -Command "config system console; set output standard; end"
    # 单独获取DHCP服务器配置
    $dhcpResult = Invoke-SshCommand -SessionId $sessionId -Command "config system dhcp server; show; end"
    $dhcpOutput = $dhcpResult.Output
    
  • 检查命令执行是否存在错误,输出可能被错误信息覆盖:

    if ($dhcpResult.Error) {
        Write-Host "命令执行错误: $($dhcpResult.Error)"
    } else {
        Write-Host "获取到的DHCP配置:`n$($dhcpResult.Output -join "`n")"
    }
    
  • 确认SSH会话状态,若会话已断开需重新建立:

    Get-SshSession -ComputerName "192.168.38.1"
    # 若状态非Connected,重新创建会话
    if ((Get-SshSession -ComputerName "192.168.38.1").State -ne "Connected") {
        New-SshSession -ComputerName "192.168.38.1" -Port 2222 -Username "xxxxxx" -Password "xxxxxx"
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:32:18