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
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. Commented Feb 3, 2021 at 13:05
  • @ADyson , yes it works fine if I am not including an array or a json_encoded array in the arguments Commented Feb 3, 2021 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. Commented Feb 3, 2021 at 13:16
  • sandbox.onlinephpfunctions.com/code/… 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. Commented Feb 3, 2021 at 13:20
  • Does this answer your question? How to pass JSON (string data) to PowerShell? Commented Feb 3, 2021 at 13:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.