CLI

Serving a HTML Page from Azure PowerShell Function

The new PowerShell language (experimental) support in Azure Function is really handy. Especially if you want to use the Azure PowerShell cmdlets to retrieve any kind of Azure Resources and display them in a HTML page. Hosting the cmdlet in Azure Function eliminates the need for a local installed Azure PowerShell module.

Here is a simple PowerShell Function that returns a Hello world HTML page:

# POST method: $req
$requestBody = Get-Content $req -Raw | ConvertFrom-Json
$name = $requestBody.name

# GET method: each querystring parameter is its own variable
if ($req_query_name) {
    $name = $req_query_name
}

$html = @'

<header>This is title</header>
<pre>Hello world</pre>
'@

Out-File -Encoding Ascii -FilePath $res -inputObject $html

Invoking the script in a browser doesn’t give us the desired result. The content gets interpreted as XML instead of HTML:

xmlresult

The reason for that is that the Content-Type is set to applicaton/xml:

xmlresponse

The output of an Azure PowerShell function is a file (called $res by default) – so how can we change the content type to text/html?

It turns out (thanks to Mikhail) that we can construct a Response Object using a JSON string (here the node definition) where we can set the content and the content-type:

$resp = [string]::Format('{{ "status": 200, "body": "{0}", "headers": {{"content-type": "text/html" }} }}', $html)
Out-File -Encoding Ascii -FilePath $res -inputObject $resp

If we invoke the function in the browser again we get the desired result:
htmlresponse

And the content-type is set to text/html:
htmldebug

Note that if your HTML contains JSON characters like double quotes or backslashes you will have to escape them. Example:

$html -replace '"', '\"'