I have to manage a cash register from PHP. If I run the following commands via cmd there are no problems. The cash register print the string perfectly.
I write the commands in this order:
powershell [System.IO.Ports.SerialPort]::getportnames() $port= new-Object System.IO.Ports.SerialPort COM1,9600,None,8,one $port.open() $port.WriteLine("1R") // Print string 1R on cash register
The problem comes when I try to do this from php. I created a web server ( XAMPP ) to ensure that it can send commands from php to the serial port . I tried various ways of writing the script, but none of them work. Here’s an example of my .php
<?php $patch = "c:\Windows\System32WindowsPowerShellv1.0powershell.exe"; $runCMD1 = $patch .'[System.IO.Ports.SerialPort]::getportnames()'; $runCMD2 = '$port= new-Object System.IO.Ports.SerialPort COM1,9600,None,8,on'; $runCMD3 = '$port.open()'; $runCMD4 = '$port.WriteLine("1R")'; exec($runCMD1, $out1); // Return COM1 exec($runCMD2, $out2); // Return Nothing exec($runCMD3, $out3); // Return Nothing exec($runCMD3, $out3); // Return Nothing ?>
Everyone can help me? Thanks.
Advertisement
Answer
Each time you execute powershell.exe
you’re passing only one line of the script to the completely new instance. That’s why it doesn’t work. You need to pass whole script to the single powershell instance. This can be done several ways:
Via StandradInput:
powershell.exe -Command - < script.ps1
Via single-line argument for Command
parameter:
powershell.exe -Command '[System.IO.Ports.SerialPort]::getportnames() ; $port= new-Object System.IO.Ports.SerialPort COM1,9600,None,8,one ; $port.open() ; $port.WriteLine("1R")'
Via Base64 string to EncodedCommand
argument :
powershell.exe -EncodedCommand 'WwBTAHkAcwB0AGUAbQAuAEkATwAuAFAAbwByAHQAcwAuAFMAZQByAGkAYQBsAFAAbwByAHQAXQA6ADoAZwBlAHQAcABvAHIAdABuAGEAbQBlAHMAKAApACAAOwAgACQAcABvAHIAdAA9ACAAbgBlAHcALQBPAGIAagBlAGMAdAAgAFMAeQBzAHQAZQBtAC4ASQBPAC4AUABvAHIAdABzAC4AUwBlAHIAaQBhAGwAUABvAHIAdAAgAEMATwBNADEALAA5ADYAMAAwACwATgBvAG4AZQAsADgALABvAG4AZQAgADsAIAAkAHAAbwByAHQALgBvAHAAZQBuACgAKQAgADsAIAAkAHAAbwByAHQALgBXAHIAaQB0AGUATABpAG4AZQAoACIAMQBSACIAKQA='
Or you can just drop temporary file to disk:
powershell.exe -File 'C:WindowsTemptempscript.ps1'