Hướng dẫn php run powershell script

Hi all,

Nội dung chính

  • “Non-Blocking” PowerShell Execution In PHP
  • Found this article valuable? Want to show your appreciation? Here are some options:
  • Reader Interactions
  • Possibilities
  • Ready to execute the Powershell code
  • Sanitize all user input before passing them to Powershell
  • How do I run a PHP script?
  • How do I run a PHP script as a service window?
  • How do I run a script in PowerShell?
  • How do I run a PHP file in Windows 10?

I come from a background of making website with php and html, I used WAMP whereas I put my web files in the www directory and it automatically ran it on localhost.

I now work in a company that gives me many projects, mostly existing ones from github and I was told to put it on my desktop and run it on localhost from there

desktop/developement/git/work-project-1 desktop/developement/git/work-project-2 ...work-project-3

So I need to now run php from the folder in my desktop, I saw that one of my colleagues were using powershell, not sure how to get it installed or running.

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.

Found this article valuable? Want to show your appreciation? Here are some options:

  1. Spread the word! Use these buttons to share this link on your favorite social media sites.
  2. Sign up to join my audience and receive email notifications when I publish new content.
  3. Contribute by adding a comment using the comments section below.
  4. Follow me on Twitter, LinkedIn, and Facebook.

I am a Toronto-based Software Engineer. I run this website as part hobby and part business.

To share your thoughts or get help with any of my posts, please drop a comment at the appropriate link.

You can contact me using the form on this page. I'm also on Twitter, LinkedIn, and Facebook.

Reader Interactions

Running a Powershell script from PHP is easier than I expected. I was pretty new to this as well, but after a while I manage to build some pretty nice automatized tasks that help a lot with small processes.

Of course, if you’re using Windows Powershell, you’ll need to run these script from a Windows Server/Client.

If you’re in a Windows environment, the best way to go is installing PHP in IIS. I recommend using the latest PHP version (at the time of writing, we’re at 7.2), you can grab it from https://php.iis.net, or you can launch the Web Platform Installer if you’ve already got it in IIS.

Possibilities

Many! You really have a huge playground here to develop whatever you need. Here’s a few examples:

  • Automate the creation of an AD account and allow access to the web end to just the Help Desk team.
    • What does this mean? You’ll no longer need to delegate permissions to the entire Help Desk team, you’ll just need to delegate permissions to the service account running the Application Pool in IIS. Also, because nobody else has permissions, you can choose the way you want this AD Account to be created (base OU, syntax, password length, settings etc).
  • Allow users to change a specific setting in their AD Account.
    • Imagine a large organization, you may want to delegate as many tasks as possible. For example, say we’re ok to trust the users to change their own Phone Numbers in AD. You can build a script that will allow to do that, at your own conditions and expose a small web interface to allow the user to see the current phone number and change it.
  • Allow the Help Desk and Desktop Teams to view a share’s NTFS permissions.
    • Once again, no need to provide access to the share, just the service account will need access. You’ll build a script that will grab the ACL from a share and return just that, based on the User’s input.

These are very basic examples of course. For instance, I’ve also built a tool that will allow Group’s managers to add/remove users to these groups. Super handy.

IIS Setup

The IIS setup is very simple. Once you’ve got PHP installed go ahead and follow these quick steps to create a new Application Pool and set it to run with a specific service account. It’s best when this service account is set as the local Admin of the server/client where it’s running from (unless you don’t need to perform any admin action).

Ready to execute the Powershell code

Let’s start with a very basic example, execute a specific powershell command. Start with creating a .php file and add this bit of code:

Now, when loading this .php page, you’ll get a list of processes running on your web server. The result should be view-friendly as we’re converting the output with ConvertTo-Html. I like to use -NoProfile to avoid loading any pre-set profile scripts that I may have set and also I prefer to call it with -executionpolicy bypass to avoid issues with the execution policy.

Next, you have a powershell script, called MyPSscript.ps1 in the same directory as the .php file and it contains:

Try  {
  #Store all processes in $MyProcesses
  $Processes = Get-Process

  #Convert $Processes in HTML
  $MyHTMLCode = $Processes | ConvertTo-HTML

  #Return the HTML code to the PHP Page
  Return $MyHTMLCode
}
Catch  {
  #Something went wrong
  Return "Oops: Something went wrong.
$($_.Exception.Message)
" }

This is how the PHP file now looks

Let’s review the code, which is called when the PHP page is launched:

  • Try to get all processes in $Processes
    • Convert the processes in HTML so that it’s human friendly when called in the browser
    • Return $MyHTMLCode to the PHP script
  • If there was an error in performing any of the actions above, return plain text (and as you can see, I added some HTML in there manually) which says that there was an error and also reports it ($_.Exception.Message).

I did this example to show you that you can really return whatever you like to the PHP page. You may even put the Shell_Exec() in a variable, and call it at a later stage:

Remember that everything within Shell_Exec() is simple command prompt code. So if you have a .ps1 script that accepts arguments, you can call them like this:

powershell.exe -executionpolicy bypass -NoProfile -File ".\MyPSscript.ps1 MyArgument1 MyArgument2"

Sanitize all user input before passing them to Powershell

This is super important. The scripts above are “safe” because you’re executing some static content. But say you’re passing something to the powershell script, something the user has inputted:

So if the user manually visits in http://myserver/mytest.php?myvar=ThisIsMyVariable, ThisIsMyVariable will now be stored in $UserVariable. If you were to pass $UserVariable without sanitizing the input, you’ll be running a huge risk. The user may actually type malicious content that will execute the script with the service account and if that account has enough rights, it can cause some serious damage.

A simple way to sanitize the string is using escapeshellarg:

I personally use also ad-hoc checks depending on the usage I need. For example, if I know the string that I need to pass to my scripts must not have dashes, semi-columns etc, I make sure I check for these chars and if found, I return an error.

How do I run a PHP script?

You just follow the steps to run PHP program using command line..

Open terminal or command line window..

Goto the specified folder or directory where php files are present..

Then we can run php code using the following command: php file_name.php..

How do I run a PHP script as a service window?

Next, please ensure that your PHP script can run normally from the command line..

Start a command prompt (Start button > Run > cmd.exe).

In the window that appears, type the full path to the PHP executable (php.exe) followed by the full path to the script you wish to run as a windows service..

How do I run a script in PowerShell?

To use the "Run with PowerShell" feature: In File Explorer (or Windows Explorer), right-click the script file name and then select "Run with PowerShell". The "Run with PowerShell" feature starts a PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.

How do I run a PHP file in Windows 10?

How to Install PHP.

Step 1: Download the PHP files. You'll need the PHP Windows installer. ... .

Step 2: Extract the files. ... .

Step 3: Configure php. ... .

Step 4: Add C:\php to the path environment variable. ... .

Step 5: Configure PHP as an Apache module. ... .

Step 6: Test a PHP file..