I am trying to write a powershell script that sends a command to a serial device and then keeps reading data coming from the device.
[System.IO.Ports.SerialPort]::GetPortNames()
Write-Host "Select Serial Port"
$portName = Read-Host -Prompt 'Input Serial Device Name'
Write-Host "Using $portName..."
$port= new-Object System.IO.Ports.SerialPort $portName, 115200, None, 8, one
$port.ReadTimeout = 1000
$port.Open()
$port.WriteLine("start\n\r")
Start-Sleep -Milliseconds 1000
while ($x = $port.ReadExisting())
{
Write-Host $x
Start-Sleep -Milliseconds 300
}
$port.Close()
The above script exits as soon as it receives 1st line from the device. I tried changing the sleep time in the while loop, but the behaviour is the same.
while ($x = $port.ReadExisting())is behaving as you're expecting?while ($port.IsOpen)from here: stackoverflow.com/a/48661245/3718361while ($port.IsOpen)did not work, but checking it in an if statement and running the script in an infinite loop worked.