Search code examples
powershellbatch-filecodesys

Trying to get Codesys to run a batch file from the HMI


So currently, I am trying to pick up this code that an intern left off for this project. I have a batch file that is run when clicked, and will execute a powershell script that will convert a generated CSV file from collected data to an Excel file. I am trying to get this process to happen automatically when a button is clicked in the HMI, but am not sure how to call a batch file in Codesys.

I have tried calling the batch file in different places of my code. Nothing will run it when the button is clicked.

FUNCTION ScriptExecute 
VAR
    szStdOout : STRING(100);    
    dutResult : sysfile.RTS_IEC_RESULT;
    szCommand: STRING;
END_VAR
szCommand := '/home/cds-apps/PlcLogic/data/ psExecuter.bat';
SysProcess.SysProcessExecuteCommand2(pszCommand:=szCommand, pszStdOut:=szStdOout, udiStdOutLen:= SIZEOF(szStdOout), pResult := ADR(dutResult));

No errors come up with this code, I just want to find a way for the batch file to be executed automatically when the user clicks the specific button. Currently the user would have to manually go into the file explorer and run the batch file themselves.


Solution

  • This is my tested code with codesys V3 on a Windows 10 machine:

    Declaration part:

    PROGRAM PLC_PRG
    VAR
        pRtsIecResult   : POINTER TO SysProcess.RTS_IEC_RESULT;
        bStart          : BOOL;
    END_VAR
    

    Implementation part:

    IF bStart 
    THEN
    
        bStart := FALSE;
    
        SysProcess.SysProcessCreate2(
            pszApplication  := 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe',
            pszCommandLine  := '-executionpolicy remotesigned -File C:\Users\fboid\Desktop\HelloWorld.ps1',
            ulFlags         := SysProcess.SYSPROCESS_CREATEFLAG_INTERACTIVE,
            pResult         := pRtsIecResult
        );
    
    END_IF
    

    As you can see I used the SysProcessCreate2 function of the SysProcess-library. Because the functions in the SysProcess-library are operating system dependent, they may not work on all platforms.

    The powershell script I executed was a very simple one:

    Write-Host 'Hello World!'
    $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")