您必须在'-Like'运算符

时间:2015-08-03 15:44:38

标签: python powershell

我想在Windows 8中通过Enable-WindowsOptionalFeature启用IIS,所以我编写了一个python程序,其代码是:

os.system('powershell -Command "%s"' % r'Enable-WindowsOptionalFeature -Online -FeatureName $(Get-WindowsOptionalFeature -Online | Where { $_.FeatureName -Like "IIS-*"} | Select-Object -ExpandProperty FeatureName)')

当我运行程序时,它显示了这个:

PS C:\Python27> ./python fr.py
At line:1 char:119
+ ... WindowsOptionalFeature -Online | Where { $_.FeatureName -Like IIS-*}  ...
+                                                                  ~
You must provide a value expression following the '-Like' operator.
At line:1 char:120
+ ... sOptionalFeature -Online | Where { $_.FeatureName -Like IIS-*} | Sele ...
+                                                          ~~~~~
Unexpected token 'IIS-*' in expression or statement.
    + CategoryInfo          : ParserError: (:) [],ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpectedValueExpression
你可以帮忙解决这个问题吗?感谢。

1 个答案:

答案 0 :(得分:0)

通过反斜杠转义双引号。 ... Where { $_.FeatureName -Like \"IIS-*\"} ...

主要的麻烦是os.system()调用完整参数字符串的命令行解析,这会在解析顺序参数时吃掉双引号。反斜杠可防止" overparsing"双引号,将它们传递给Powershell。一个例子:

>>> os.system('powershell -command "%s"' % r'get-process | where {$_.name -like \"powershell*\"}')

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    286      24    57948      54196   606     0,51   5336 powershell
    501      32    46540      58164   239     7,58   5456 powershell