I need to know how I can continuously read data in from the COM port and dump it to a file using Windows Powershell. While I am reading data in, I also need to monitor the data being read in and, depending on what the last line that was read, write data to the COM port.
To open the COM port in Powershell, I am doing this:
[System.IO.Ports.SerialPort]::getportnames()
$port= new-Object System.IO.Ports.SerialPort COM3,115200,None,8,one
$port.open()
To read data in to the COM port, I am doing this:
$line=$port.ReadLine()
My initial thought was to have the main Powershell script open the COM port. Then it would start a background/child task to continuously read data in from COM port and dump it to a file. While that child task is running, the parent would then continuously monitor the file and write to the COM port when needed.
When I tried to do that, the child could not read data in from the COM port because the parent had it open and the child did not inherit that permission from the parent.
Any ideas on how I can accomplish this?
1) Click Start. 2) Click Control Panel in the Start menu. 3) Click Device Manager in the Control Panel. 4) Click + next to Port in the Device Manager to display the port list.
To configure the Serial Port for your device, on your computer go to Control Panel - Device Manager, select “High-Speed USB Serial Port (Com X)”, right click and select Properties. Click the Features tab. This tab is used to change the COM port number and configure the port.
Using Netstat command: Open a CMD prompt. Type in the command: netstat -ano -p tcp. You'll get an output similar to this one. Look-out for the TCP port in the Local Address list and note the corresponding PID number.
Simple answer: while loop. Calling functions to decide when to write data. Use child task and scripts to handle/process/get data but keep the communication in the same task/script. I used this code to read from my Ardunio:
$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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With