2

I am trying to pass a variable from PHP to a powershell script.

My PHP code is :

shell_exec("powershell.exe -ExecutionPolicy Bypass -NoProfile -InputFormat none -file test.ps1 '$txt' < NUL ");

And I am trying to capture it in powershell using :

param (
  [string]$txt
)

Add-Content "test.txt" $txt

The $txt is a string variable as I can write it in a txt file from PHP. I do not know exactly where I am wrong as the powershell is executed.

5
  • What's the problem? Is test.txt not getting created? Commented Jan 21, 2022 at 12:32
  • The text.txt is created, but empty. No $txt variable value is parsed. Commented Jan 21, 2022 at 13:04
  • 1
    According to the docs the -InputFormat parameter supports 'Text' or 'XML'. You give it 'none'. Try changing that to Text. And shouldn't < NUL be > $null ?? Commented Jan 21, 2022 at 15:05
  • @mklement0 Sorry, I did not get the chance to check your solution until now. Many thanks, it did fix my problem. Commented Jan 23, 2022 at 13:29
  • No worries; glad to hear it worked; my pleasure. Commented Jan 23, 2022 at 14:02

1 Answer 1

1

Use the following:

shell_exec("powershell.exe -ExecutionPolicy Bypass -NoProfile -file test.ps1 \"$txt\"");

Note: If the value of $txt had embedded " chars., they'd need to be escaped.

  • The PowerShell CLI doesn't recognize '...' quoting when passing arguments to a script file executed via -File; use "...".

    • Your attempt with '$txt' shouldn't have resulted in an empty file, but it would have included the ' chars. as part of the argument; if $txt happens to contain spaces, each space-separated word would have become a separate argument, with the first starting with ' and the last ending in '
  • Since you're not providing input via stdin, there is no need for -inputFormat and < NUL

Sign up to request clarification or add additional context in comments.

Comments

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.