PowerShell PHP JSON Example

I realized a small example might be useful to compliment https://jthiede.wordpress.com/2013/10/01/jquery-getjson-from-powershell-via-php-on-iis-a-frustrating-gotcha/. Below is a very basic example of getting JSON from PowerShell via PHP. Exciting.

Fruits.ps1 PowerShell script

#Creates a string of JSON-looking text and returns/prints it to the console

$a = “apple”

$b = “banana”

$c = “coconut”

$json = “{`n`”a`”: `”$a`”,`n`”b`”: `”$b`”,`n`”c`”: `”$c`”`n}”

Return $json

If using later versions of PowerShell (3 and up), you can also simplify this with

#Build a hash table and use PowerShell's own json conversion

$json = @{"a" = "apple";"b" = "banana";"c" = "coconut"} | ConvertTo-Json

Fruits.php PHP file

Note that this PHP script invokes PowerShell while bypassing the execution policy. This is not safe for a production environment, but suffices as an example. Also note that backslashes are escaped (e.g.: “\\” instead of “\”).


echo(shell_exec("mode 256,50 &amp; powershell -NoProfile -ExecutionPolicy Bypass -File C:\\scripts\\fruits.ps1 &lt; NUL")); ?&gt;


Note that this bit of JS depends on jQuery

function getFruit(){
url: "fruits.php",
dataType: "json",
mimeType: "textPlain",
success: function(data){


This should pop up an alert that says “apple.” Again, so exciting.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s