【问题标题】:How to Wrap Powershell around IIS AppCmd如何围绕 IIS AppCmd 包装 Powershell
【发布时间】:2021-01-04 16:31:13
【问题描述】:

我正在尝试将 Powershell 包裹在 AppCmd 周围以执行一些安全合规性检查。我决定这样做而不是使用 powershell 的 Get-WebConfiguration 命令,因为对于所有这些检查,安全策略已经提供了相应的 AppCmd 命令。因此,与其花太多时间尝试锻炼等效的 Get-WebConfiguration 命令,我决定编写一个函数,以变量形式获取提供的 AppCmd 命令和参数,在 powershell 中运行它们,并可能将结果传递给另一个函数.

我在将变量值传递给 AppCmd 时遇到了很多问题。 以下代码有效:

$appCmd = "C:\Windows\system32\inetsrv\appcmd.exe"
& $appCmd list config /section:system.web/authentication /text:forms.requireSSL

到目前为止一切顺利。 现在,以下代码会导致错误:

$appCmd = "C:\Windows\system32\inetsrv\appcmd.exe"
$appcmd_args = "list config /section:system.web/authentication /text:forms.requireSSL"

& $appCmd $appcmd_args

错误显示:

Object 'LIST CONFIG /SECTION:SYSTEM.WEB/AUTHENTICATION /TEXT:FORMS.REQUIRESSL' is not supported.  Run 'appcmd.exe /?' to display supported objects.

我阅读了之前的一篇文章,该文章建议在将变量传递给 AppCmd 时使用 ${}。所以,试试这个:

$appCmd = "C:\Windows\system32\inetsrv\appcmd.exe"
$appcmd_args = "list config /section:system.web/authentication /text:forms.requireSSL"

& $appCmd ${appcmd_args}

我可能做错了,所以我得到了与上面相同的错误。我还注意到以下代码出现了同样的错误:

$appCmd = "C:\Windows\system32\inetsrv\appcmd.exe"
& $appCmd "list config /section:system.web/authentication /text:forms.requireSSL"

也许需要进行某种类型的转换或修整?

所有 AppCmd 命令和参数都将通过变量提供,因此,如果这种技术不起作用,我的计划就会落空。我显然错过了一些东西。能否请您提供解决方案?

【问题讨论】:

    标签: powershell iis appcmd


    【解决方案1】:

    由于appcmd.exe 需要用空格分隔的参数,因此您不能将其全部作为一个字符串发送。我会采用其中一种方法。

    用逗号分隔每个参数,然后将它们分开

    $appcmd_args = "list", "config", "/section:system.web/authentication", "/text:forms.requireSSL"
    
    & $appCmd $appcmd_args
    

    或者你可以像这样拆分内联参数

    $appcmd_args = "list config /section:system.web/authentication /text:forms.requireSSL"
    
    & $appCmd (-split $appcmd_args)
    

    【讨论】:

    • 感谢@Doug 的回复。让我试一试!
    • & $appCmd (-split $appcmd_args) 有效!谢谢。
    【解决方案2】:

    经过数小时的反复试验,我发现这行得通。

    $appCmd = "C:\Windows\system32\inetsrv\appcmd.exe"
    $appcmd_args = "list config /section:system.web/authentication /text:forms.requireSSL"
    $AppCmd_Command = [string]::Format("{0} {1}", $appCmd, $appcmd_args)
    
    iex $AppCmd_Command
    

    【讨论】:

    • 几乎总是希望避免使用Invoke-Expression
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2015-03-10
    • 2011-09-30
    相关资源
    最近更新 更多