Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run appCmd in PowerShell to add custom headers to the Default Web Site

Please help me figure out how to properly escape the arguments so they work when calling appcmd inside of powershell.

My script looks like this:

$defaultWebSite = "Default Web Site"
$appCmd = "C:\windows\system32\inetsrv\appcmd.exe"
$addHeaderP3P = "set config ""$defaultWebSite"" -section:system.webServer/httpProtocol /+""customHeaders.[name='P3P',value='policyRef=`\`"/w3c/p3p.xml`\`",CP=`\`"DSP COR NID OUR COM PRE`\`"']`""

Write-Output "Here's the argument string: " $addHeaderP3P



Write-Output "`nInvoke Result:"
Invoke-Expression "$appCmd $addHeaderP3P"


Write-Output "`n& Result:"
& $appCmd --%"$addHeaderP3P"

The output is this when running inside powershell_ise:

PS C:\Users\robert.bratton> D:\Junk\p3pheader.ps1
Here's the argument string: 
set config "Default Web Site" -section:system.webServer/httpProtocol /+"customHeaders.[name='P3P',value='policyRef=\"/w3c/p3p.xml\",CP=\"DSP COR NID OUR COM PRE\"']"

Invoke Result:
Failed to process input: The parameter 'COR' must begin with a / or - (HRESULT=80070057).


& Result:
Failed to process input: The parameter 'NID' must begin with a / or - (HRESULT=80070057).

This works from the command line

"C:\windows\system32\inetsrv\appcmd.exe" set config "Default Web Site" -section:system.webServer/httpProtocol /+"customHeaders.[name='P3P',value='policyRef=\"/w3c/p3p.xml\",CP=\"DSP COR NID OUR COM PRE\"']"

Thanks for your help!

like image 753
Robert Bratton Avatar asked Feb 05 '14 17:02

Robert Bratton


People also ask

How do I run AppCmd?

To start Appcmd.exe At the Command Prompt, type cd %windir%\system32\inetsrv, and then press ENTER.

What is Inetsrv AppCmd exe?

Introduction. The appcmd.exe is a single command, used to manage IIS 7 and above. It is used to manage the Server without using a graphical administration tool. The appcmd is located in C:\Windows\System32\inetsrv (%systemroot%\system32\inetsrv\) directory.


1 Answers

Try it like this:

$env:defaultWebSite = "Default Web Site"
$appCmd = "C:\windows\system32\inetsrv\appcmd.exe"

& $appCmd --% set config "%defaultWebSite%" -section:system.webServer/httpProtocol /+customHeaders.[name='P3P',value='policyRef="/w3c/p3p.xml",CP="DSP COR NID OUR COM PRE"']

If you use any variables after the --% the have to be environment variables.

like image 55
Keith Hill Avatar answered Sep 20 '22 18:09

Keith Hill