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

如何获取PSSession远程会话中执行的端口连通性测试结果

问题原因
  • 你第一次执行Invoke-Command时,脚本块内定义的$RsTestResults是远程会话的临时局部变量,脚本块执行完成后就会被回收,不会持久保存在远程会话中
  • 你第二次调用Invoke-Command时没有指定关联之前创建的$RemoteSession,相当于在本地环境执行脚本块,本地自然不存在该变量
解决方案

方案1(推荐):直接在单次远程调用中返回结果

不需要单独存储变量再读取,直接让远程执行的脚本块把连通性结果返回即可,代码如下:

# 创建远程会话
$RemoteSession = New-PSSession -ComputerName MyRemoteVM

# 远程执行端口测试并直接返回结果
$LocalResults = Invoke-Command -Session $RemoteSession -ScriptBlock {
    # 替换为实际的目标主机名/IP和端口
    $targetHost = "2ndRemoteVM"
    $targetPort = 2ndRemoteVMPort
    try {
        $tcpClient = New-Object System.Net.Sockets.TcpClient -ArgumentList $targetHost, $targetPort
        $connectResult = $tcpClient.Connected
        $tcpClient.Close()
        return $connectResult
    } catch {
        # 连接失败时返回false
        return $false
    }
}

# 测试完成后关闭远程会话释放资源
Remove-PSSession $RemoteSession

执行完成后$LocalResults的值为$true代表端口连通,$false代表端口不通。

方案2:先存储到远程会话全局变量再读取

如果确实需要分两步操作,需要把变量存储到远程会话的全局作用域,读取时也指定同一会话:

# 创建远程会话
$RemoteSession = New-PSSession -ComputerName MyRemoteVM

# 第一步:远程执行测试,结果写入远程会话全局变量
Invoke-Command -Session $RemoteSession -ScriptBlock {
    $targetHost = "2ndRemoteVM"
    $targetPort = 2ndRemoteVMPort
    try {
        $tcpClient = New-Object System.Net.Sockets.TcpClient -ArgumentList $targetHost, $targetPort
        $global:RsTestResults = $tcpClient.Connected
        $tcpClient.Close()
    } catch {
        $global:RsTestResults = $false
    }
}

# 第二步:指定同一会话,读取远程全局变量
$LocalResults = Invoke-Command -Session $RemoteSession -ScriptBlock { $global:RsTestResults }

# 关闭会话
Remove-PSSession $RemoteSession
补充说明

如果你使用的是PowerShell 5.1及以上版本,可以直接用内置的Test-NetConnection命令简化端口测试逻辑:

$LocalResults = Invoke-Command -Session $RemoteSession -ScriptBlock {
    (Test-NetConnection -ComputerName "2ndRemoteVM" -Port 2ndRemoteVMPort).TcpTestSucceeded
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:06:05