Since PowerShell is now open source and cross-platform, we can now perform PowerShell magic right inside Linux boxes. We can execute PowerShell scripts (or commands) directly from within PHP code on Linux machines.
We can even place PowerShell commands right inside our PHP code without using an external script.
No more dependence on Windows/Microsoft operating systems! If this isn’t exciting stuff, what is?!
Before you can execute PowerShell scripts from PHP on a Linux machine however, you first need to install PowerShell Core on the Linux machine in question. My previous article discussed how to do that on Ubuntu.
If you have already installed PowerShell on your Linux box, you can use a number of similar PHP commands to execute PowerShell code.
Any of these commands should work:
/* . */ shell_exec('pwsh -File /your/path/to/file.ps1'); // Or exec('pwsh -File /your/path/to/file.ps1'); // Or system('pwsh -File /your/path/to/file.ps1'); // Or passthru('pwsh -File /your/path/to/file.ps1'); /* . */
The commands are all similar with slight differences in their behavior:
- shell_exec returns the full output of the command at the end of execution. Not just the last line of generated output.
- exec returns only the last line of generated output during program execution.
- system displays all code execution output immediately. It is used to show text data.
- passthru also displays all code execution output immediately. But it is used for binary (or raw) data.
With both shell_exec and exec, you can handle the output yourself, but system and passthru displays the output immediately and will not let you customize it.
The pwsh command is used to start Powershell. In the above examples, we’re passing a .ps1 file to be executed.
You can also execute a PowerShell command directly by using -Command flag instead of the -File flag which was used above.
“Non-Blocking” PowerShell Execution In PHP
If you want to trigger a PowerShell process via PHP without “blocking” your PHP process, execute the script like this:
shell_exec('pwsh -File /your/path/to/file.ps1 > /dev/null 2>&1 &');
When coded like that, PHP will simply start the PowerShell process and move on to executing the next line of PHP code without waiting for the Powershell script to finish executing. No messages from the PowerShell process will be displayed.
I find this useful in certain scenarios, like firing off a request to deallocate an Azure VM.
When I deallocate VMs, I usually don’t want my PHP process to wait until the deallocation completes.
I like to send the command and then move on to other stuff. The /dev/null construct used above helps to achieve this.
Leave a Reply