如何在Powershell中连续读取串行COM端口并偶尔写入COM端口

hea*_*ook 5 powershell

我需要知道如何从 COM 端口连续读取数据并使用 Windows Powershell 将其转储到文件中。在读取数据时,我还需要监视正在读取的数据,并根据读取的最后一行内容将数据写入 COM 端口。

要在 Powershell 中打开 COM 端口,我这样做:

[System.IO.Ports.SerialPort]::getportnames()
$port= new-Object System.IO.Ports.SerialPort COM3,115200,None,8,one
$port.open()
Run Code Online (Sandbox Code Playgroud)

要将数据读入 COM 端口,我这样做:

$line=$port.ReadLine()
Run Code Online (Sandbox Code Playgroud)

我最初的想法是让主 Powershell 脚本打开 COM 端口。然后它会启动一个后台/子任务,从 COM 端口连续读取数据并将其转储到文件中。当该子任务正在运行时,父任务将持续监视文件并在需要时写入 COM 端口。

当我尝试这样做时,孩子无法从 COM 端口读取数据,因为父母将其打开并且孩子没有从父母那里继承该权限。

关于我如何做到这一点的任何想法?

the*_*itz 5

简单的答案:while 循环。调用函数来决定何时写入数据。使用子任务和脚本来处理/处理/获取数据,但将通信保持在同一任务/脚本中。我使用此代码从我的 Arduio 中读取:

$COM = [System.IO.Ports.SerialPort]::getportnames()

function read-com {
    $port= new-Object System.IO.Ports.SerialPort $COM,9600,None,8,one
    $port.Open()
    do {
        $line = $port.ReadLine()
        Write-Host $line # Do stuff here
    }
    while ($port.IsOpen)
}
Run Code Online (Sandbox Code Playgroud)

  • 如果 getportnames() 返回多个 COM 端口,`$port.Open()` 将失败。这也不能解决不以换行符或回车符结尾的读取行,例如 linux 命令行提示符。 (2认同)