Search code examples
phppowershellpowershell-7.4

I can not run php shell_exec with powershell 7.4


I have a powershell script that would output system variable values:

env_output.ps1

$Env:UserDomain
$Env:ComputerName
$Env:UserName

I can get an output when I use this php function to call powershell v5 file

$output_switch = shell_exec('powershell.exe -File C:\inetpub\env_output.ps1');
print_r ($output_switch);

But when I switch to to use powershell v7.4, I got no output.

$output_switch = shell_exec('pwsh.exe -File C:\inetpub\env_output.ps1');
print_r ($output_switch);

Windows 2019 Server with IIS and PHP.

Both powershell executables are in the system path variable.


Solution

  • Since I couldn't call PS 7.4 executable directly to execute a script, I implemented a convoluted work-around by calling PS5 script that would call PS7.4 to execute the script I want. To get the output of the script, I redirect it to a temp file and then read it in php.

    I will use this setup temporarily until I can figure out why I can't call PS 7.4 executable directly from php.

    php code

    shell_exec('powershell.exe -File C:\inetpub\ps5-calling7.ps1');
    $output = "C:\\inetpub\\env_output.tmp";
    

    ps5-calling7.ps1

    Start-Process pwsh.exe -ArgumentList "C:\inetpub\env_output.ps1" -wait -RedirectStandardOutput "env_output.tmp";