0

I am trying to transport a PHP array (from index.php) to a Powershell function (ps_scripts.ps1) as an argument. However, am getting an error(error below). I am using the EXEC function in PHP to pass arguments to the Powershell function.

PHP Code:

            $psPath = "powershell.exe -InputFormat none -ExecutionPolicy ByPass  -NoProfile ";
            $psDIR = "C:\\xampp\\htdocs\\";
            $psScript = "ps_scripts.ps1";
            $runScript = $psDIR. $psScript;
            $runCMD = $psPath." ".$runScript." 2>&1 "; 


            $parameter_2 = "testdata";
            $array = array("Peter"=>24, "Ben"=>"Hello");
            $encoded_data = json_encode($array);
            exec($runCMD . "example_function_name \"" . $encoded_data . "\"" . " \"" . $parameter_2 . "\"", $output, $retval);

Powershell Code - ps_scripts.ps1:

            $arguments = $args;
            function example_function_name
            {
              $sData = $arguments[0] | ConvertFrom-Json
              echo $sData;
            }

Error:

            Array ( [0] => At line:1 char:70 [1] => + ... htdocs\ps_scripts.ps1 example_function_name {Peter:24,Ben:Hell ... [2] => + ~ [3] => Missing argument in parameter list. [4] => + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException [5] => + FullyQualifiedErrorId : MissingArgument [6] => ) 1
Manu
  • 23
  • 5
  • Did you do any basic debugging? I suggest you `echo $runCMD . "example_function_name \"" . $encoded_data . "\"" . " \"" . $parameter_2 . "\"", $output, $retval` and see if it looks as you expect, and whether, if you copy/paste that into a powershell terminal, it works. – ADyson Feb 03 '21 at 13:05
  • @ADyson , yes it works fine if I am not including an array or a json_encoded array in the arguments – Manu Feb 03 '21 at 13:10
  • Ok. But that wasn't quite what I asked. So it fails when you put the JSON in there? I'd guess you probably have quoting issues. – ADyson Feb 03 '21 at 13:16
  • http://sandbox.onlinephpfunctions.com/code/63c729a744824aa58b0c21df1fa3730aa89bdb05 shows that you're likely to have quote issues - the quote marks within the JSON will confuse PS as to where the parameter starts and ends. I don't know PS that well... will it accept single-quoted strings? If not you might have to escape the strings in the JSON. – ADyson Feb 03 '21 at 13:20
  • Does this answer your question? [How to pass JSON (string data) to PowerShell?](https://stackoverflow.com/questions/53490414/how-to-pass-json-string-data-to-powershell) – ADyson Feb 03 '21 at 13:21

0 Answers0