问题描述
我正在尝试将 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 命令和参数都将通过变量提供,因此,如果此技术不起作用,我的计划就会分崩离析。我显然错过了一些东西。你能就解决方案提出建议吗?
解决方法
由于 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)
,
经过数小时的反复试验,我发现这可行。
$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