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.
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 "..."
.
'$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