【问题标题】:How to run appCmd in PowerShell to add custom headers to the Default Web Site如何在 PowerShell 中运行 appCmd 以将自定义标头添加到默认网站
【发布时间】:2014-03-02 07:19:57
【问题描述】:

请帮助我弄清楚如何正确转义参数,以便它们在 powershell 中调用 appcmd 时起作用。

我的脚本如下所示:

$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"

在 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).

这可以从命令行运行

"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\"']"

感谢您的帮助!

【问题讨论】:

    标签: powershell iis-7 escaping appcmd p3p


    【解决方案1】:

    试试这样:

    $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"']
    

    如果您在--% 之后使用任何变量,则必须是环境变量。

    【讨论】:

    • 感谢您的建议。我收到关于缺少关闭报价的错误。字符串开始: At line:4 char:180 + & $appCmd --% set config "%defaultWebSite%" -section:system.webServer/httpProtocol /+""customHeaders.[name='P3P',value='policyRef =\"/w3c/p3p.xml\",CP=\"DSP COR NID OUR COM PRE\"']
    • 我将您上面列出的示例中的所有内容从-section 复制到最后,因为它可以正常工作。但是,您可能已经进行了更改以从 PowerShell 中进行这项工作。在您指定 --% PowerShell 时,它的解析更像 cmd.exe。让我尝试摆脱 PowerShell 变通办法。
    最近更新 更多