param( [switch]$ListPorts, [string]$PortName = 'COM3', [int]$Baud = 9600, [string]$Parity = 'None', [string]$Send, [int]$Listen = 0, [switch]$Interactive ) if ($ListPorts) { [System.IO.Ports.SerialPort]::GetPortNames() | Sort-Object return } $parityValue = [Enum]::Parse([System.IO.Ports.Parity], $Parity) $sp = New-Object System.IO.Ports.SerialPort($PortName, $Baud, $parityValue, 8, [System.IO.Ports.StopBits]::One) $sp.ReadTimeout = 300 $sp.NewLine = "`n" $sp.Encoding = [System.Text.Encoding]::ASCII try { $sp.Open() Write-Host "opened $PortName @ $Baud 8N1, Ctrl+C to exit" if ($Send) { $payload = $Send -replace '\\n', "`n" -replace '\\r', "`r" $sp.Write($payload) Write-Host ("TX: " + ($payload -replace "`n", '\n' -replace "`r", '\r')) } if ($Interactive) { while ($true) { $line = Read-Host 'TX' if ([string]::IsNullOrEmpty($line)) { continue } $sp.Write($line + "`n") Start-Sleep -Milliseconds 200 try { while ($true) { $rx = $sp.ReadExisting() if ($rx) { Write-Host ("RX: " + ($rx -replace "`n", '\n' -replace "`r", '\r')) } break } } catch {} } } if ($Listen -gt 0) { $deadline = (Get-Date).AddSeconds($Listen) $buffer = '' while ((Get-Date) -lt $deadline) { try { $chunk = $sp.ReadExisting() if (-not $chunk) { Start-Sleep -Milliseconds 50 continue } $buffer += $chunk $parts = $buffer -split "`n" $buffer = $parts[-1] $lines = $parts[0..($parts.Count - 2)] foreach ($line in $lines) { Write-Host ("RX: " + ($line -replace "`r", '') -replace '`n', '') } } catch {} } } } finally { if ($sp.IsOpen) { $sp.Close() } }