Is it possible to make an RS232 mini char with PowerShell?

Metaconta 41 Reputation points
2023-01-21T10:45:55.7733333+00:00

Good:

I want to make a nice mini chat for the serial port between two PCs. Since I am not familiar, I want help. I have three programs that do the same thing in C#, VB .net and C++ .net in mini chat console mode and it works between them. At least I leave the C# source code if someone compares it and manages to do it. If you want another language, tell it and I'll upload the full version.

Regards.

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,299 questions
0 comments No comments
{count} votes

Accepted answer
  1. Limitless Technology 44,101 Reputation points
    2023-01-23T16:14:01.0833333+00:00

    Hello there,

    I found the below script on an thread which explains how to read and write to/from the serial port using Powershell.

    #Returns a list of all the currently available serial ports.

    #Creates a new COM port object for COM5 with a baud rate of 9600.

    $port = new-Object System.IO.Ports.SerialPort COM5,9600,None,8,one

    #Open the connection.

    $port.open()

    $port.WriteLine("some string") #Sends string.

    $port.ReadLine() #Receives string.

    #Close the connection when done.

    $port.Close()

    Hope this resolves your Query !!

    --If the reply is helpful, please Upvote and Accept it as an answer–

    1 person found this answer helpful.

5 additional answers

Sort by: Most helpful
  1. Rich Matheisen 45,671 Reputation points
    2023-01-21T19:42:58.4633333+00:00

    If you've already accomplished the goal by using C# then duplicating it may be easy -- unless you're making use if asynchronous I/O. The same .Net classes are usable in PowerShell, but I'm not sure how PowerShell would use asynchronicity.

    0 comments No comments

  2. Metaconta 41 Reputation points
    2023-01-21T20:27:59.7033333+00:00

    Hello:

    Don't worry about the synchronization, since everything is by default. I leave the C# source code.

    I hope someone will be able to convert the code from C# to PowerShell and do the same.

    I have the comments in Spanish. If you want to translate the C# code into PowerShell, I can comment the program comments into English, so you can understand it better. `using System; using System.IO; using System.IO.Ports; using System.Text; using System.Threading;

    namespace Chat_Consola_04 { class Program { static bool _continua; static SerialPort Puerto_serie;

        static void Main(string[] args)
        {
            const int MAXIMA_LONGITUD = 40000;
            string COM = "";
            string nombre;
            string mensaje;
            string titulo = "Mini chat C#";
    
            StringComparer comparaString = StringComparer.OrdinalIgnoreCase;
            Thread readThread = new Thread(Leer);
    
            #region Configuración ventana.
            // Título de la ventana.
            Console.Title = titulo;
    
            // Tamaño de la ventana, x, y, o ancho y alto.
            const byte ANCHO_X = 70, ALTO_Y = 25;
            Console.SetWindowSize(ANCHO_X, ALTO_Y);
    
            // Color de fondo.
            Console.BackgroundColor = ConsoleColor.Green;
    
            // Color de las letras.
            Console.ForegroundColor = ConsoleColor.Black;
    
            // Limpiar pantalla y dejarlo todo en color de fondo.
            Console.Clear();
    
            // Visible el cursor.
            Console.CursorVisible = true;
            #endregion
    
            #region Configuración puerto serie.
            // Crear un nuevo objeto SerialPort con la configuración predeterminada.
            Puerto_serie = new SerialPort();
    
            // Codificar a UTF-8 para que se vean bien las tildes, ñ y otros caracteres.
            Puerto_serie.Encoding = Encoding.UTF8;
    
            // Obtenga una lista de nombres de puertos serie.
            string[] puertos = SerialPort.GetPortNames();
    
            Console.WriteLine("Se encontraron los siguientes puertos series:");
    
            // Muestre el nombre de cada puerto en la consola.
            foreach (string puerto in puertos)
            {
                Console.WriteLine(puerto);
            }
    
            // Configuración.
            Console.Write(@"
    

    Introduzca un número para seleccionar puerto COM. Por ejemplo el 4, sería COM4.

    Puerto: "); COM = Console.ReadLine(); // Escribir el número del puerto. Console.Clear(); // Limpiar pantalla.

            Puerto_serie.PortName = "COM" + COM; // Número del puerto serie.
    
            // Configuración del puerto serie.
            Puerto_serie.BaudRate = 115200;
            Puerto_serie.Parity = Parity.None;
            Puerto_serie.StopBits = StopBits.One;
            Puerto_serie.DataBits = 8;
            Puerto_serie.Handshake = Handshake.None;
            Puerto_serie.RtsEnable = true;
    
            // Establecer los tiempos de espera de lectura / escritura.
            Puerto_serie.ReadTimeout = 500; // 500 Milisegundos.
            Puerto_serie.WriteTimeout = 500; // 500
    
            // Comprueba si puede abrir el puerto serie.
            try
            {
                Puerto_serie.Open(); // Abrir el puerto serie.
            }
    
            // En caso que diera algún error como que no encuentra el puerto seleccionado
            // muestra una excepción.
            catch (IOException)
            {
                Console.ForegroundColor = ConsoleColor.Red; // Texto en rojo.
                Console.CursorVisible = false;
                Console.SetCursorPosition(16, 6);
                Console.WriteLine(@"El puerto " + Puerto_serie.PortName + @" no existe
                o no lo encuentra.");
                Console.ReadKey();   // Pulse cualquier tecla.
                Environment.Exit(1); // Salir de la aplicación.
            }
    
            // Se ha denegado el acceso al puerto.
            catch (UnauthorizedAccessException)
            {
                Console.ForegroundColor = ConsoleColor.Red; // Texto en rojo.
                Console.CursorVisible = false;
                Console.SetCursorPosition(16, 6);
                Console.WriteLine(@"Se ha denegado el acceso al puerto " + Puerto_serie.PortName +
                                "" +
                                "\nPuede estar el puerto escogido en uso.\n" +
                                "Elija un puerto diferente o desactiva el que está en uso.");
                Console.ReadKey();   // Pulse cualquier tecla.
                Environment.Exit(1); // Salir de la aplicación.
            }
            #endregion
    
            _continua = true;
            readThread.Start();
    
            // Mostrar texto Nombre y se
            Console.Write("Nombre: ");
    
            // guarda en la variable nombre.
            nombre = Console.ReadLine();
    
            // Se muestra el nombre o nick y el puerto seleccionado al final del título de la ventana.
            Console.Title = titulo + "- Nick: " + nombre + " - COM: " + COM;
    
            Console.WriteLine("Escriba /salir para salir.");
    
            while (_continua)
            {
                // Cualquier caracter recibido se guarda en la variable mensaje.
                //mensaje = Console.ReadLine();
    
                #region Enviar más de 255 caracteres.
                // #########################################################################
                Stream entradaDeDatos = Console.OpenStandardInput();
                byte[] buffer = new byte[MAXIMA_LONGITUD];
                int numerosBytesLeidos = entradaDeDatos.Read(buffer, 0, MAXIMA_LONGITUD);
    
                char[] chars = Console.InputEncoding.GetChars(buffer, 0, numerosBytesLeidos);
                mensaje = new string(chars);
                // #########################################################################
                #endregion
    
                // Compara /salir con el mensaje /salir si lo haz escrito igual.
                // ¿Escribiste la palabra /salir?
                if (comparaString.Equals("/salir\r\n", mensaje))
                {
                    // Sí. Entonces, pone esta variable _continue en false.
                    _continua = false;
                }
                // No. Entonces, envía por el puerto serie tu nick
                // y mensaje que haz escrito.
                else
                {
                    Puerto_serie.WriteLine(String.Format("<{0}>: {1}", nombre, mensaje));
                }
            }
    
            // Bloquea el subproceso.
            readThread.Join();
    
            // Cierra el puerto serie.
            Puerto_serie.Close();
        }
    
        // Lee mensaje recibido.
        public static void Leer()
        {
            // Si _continua es true se ejecuta todas las instrucciones dentro de while.
            while (_continua)
            {
                try
                {
                    // Almacena en la variable mensaje cualquier caracter o mensaje recibido.
                    string mensaje = Puerto_serie.ReadLine();
    
                    // Muestra en pantalla mensaje recibido.
                    Console.WriteLine(mensaje);
                }
                catch (TimeoutException) { }
            }
        }
    }
    

    }`

    Greetings and blessings.


  3. Metaconta 41 Reputation points
    2023-01-22T08:30:34.6733333+00:00

    Good morning Mr. MotoX80:

    I want to do it in PowerShell for a change. I also have it done in Visual Basic .net and C++ .net, precisely with Visual Studio Community 2022.

    I'm comparing languages. Now I have to do it with PowerShell. I don't understand this language that's why I ask for help.

    Have a good day and thanks for your answer.


  4. Metaconta 41 Reputation points
    2023-01-22T11:14:04.51+00:00

    Thanks. I spend half my life learning to use PowerShell well. My idea is to have the program and make it work.

    0 comments No comments