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

如何在Windows的两个PowerShell终端窗口间传递字符串?

在Windows PowerShell终端窗口间互发字符串的实现方法

Unix环境下的现有方案

在Unix环境中,我们可以通过/dev/ttyS串行设备或/dev/pty伪终端在终端窗口间发送字符串,只要知晓对应的tty/pty编号,操作十分简单:

# 在/dev/pty1窗口执行写入操作:
echo -e "\nHello! \n" >/dev/pty0

# 此时/dev/pty0窗口会接收到:
Hello! 

注:Cygwin/Bash版本存在一个bug,会干扰字符\n及其前面的内容,除非\n前面是空格。

该方法在MSYS/Cygwin环境中同样适用。

Windows环境下的需求与现状

那在Windows系统中,能否在两个PowerShell终端窗口间实现类似的跨窗口发消息功能?

目前已知可以通过COM串行设备发送字符串,示例如下:

echo "Hello!" > \\.\\COM3

但Windows终端Shell并没有关联的COM端口,也没有其他像Unix那样直接可访问的伪终端设备文件。COM端口的设置位于注册表路径:HKLM:\SYSTEM\CurrentControlSet\Control\COM Name Arbiter\Devices

可行的Windows实现方案

Windows没有Unix风格的伪终端设备文件,但可以通过以下几种原生机制实现PowerShell窗口间的通信:

1. 命名管道(Named Pipes)

命名管道是Windows原生的进程间通信机制,适合本地PowerShell窗口之间传递数据:

  • 接收端窗口:运行以下命令监听管道:
$pipeName = "MyPowerShellPipe"
$pipe = New-Object System.IO.Pipes.NamedPipeServerStream($pipeName, [System.IO.Pipes.PipeDirection]::In)
$pipe.WaitForConnection()
$reader = New-Object System.IO.StreamReader($pipe)
while ($true) {
    $message = $reader.ReadLine()
    if (-not $message) { break }
    Write-Host "收到消息:$message"
}
$reader.Close()
$pipe.Close()
  • 发送端窗口:运行以下命令发送消息:
$pipeName = "MyPowerShellPipe"
$pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", $pipeName, [System.IO.Pipes.PipeDirection]::Out)
$pipe.Connect()
$writer = New-Object System.IO.StreamWriter($pipe)
$writer.WriteLine("Hello from another PowerShell!")
$writer.Flush()
$writer.Close()
$pipe.Close()

2. PowerShell远程会话(PSRemoting)

如果启用了PowerShell远程功能,可以直接向目标窗口的会话发送命令:

  • 先获取目标PowerShell窗口的会话ID:
Get-Process pwsh | Select-Object Id, MainWindowTitle
  • 向目标会话发送消息:
Invoke-Command -Session (Get-PSSession -Id <会话ID>) -ScriptBlock { Write-Host "Hello from remote session!" }

注:需要提前以管理员权限运行Enable-PSRemoting -Force启用远程功能。

3. ConPty伪控制台

Windows的ConPty提供了伪控制台支持,但需要通过API调用实现,PowerShell中可借助.NET或第三方模块简化操作,适合需要底层控制的场景,不过实现复杂度较高。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 02:23:14