Powershell:出乎意料的令牌

时间:2014-03-02 20:27:28

标签: powershell

这一定是显而易见的,但我不能让它发挥作用。我正在尝试传输用于构建$ classKey的对象,这反过来导致删除所需的软件(amd64或i386)。嗯,这里是代码:

$name = @("softwareName1", "softwareName2", "softwareName3")
$strComputer = "localhost"
$getWmiClass = get-wmiobject -class "SampleProductsList32" -namespace "root\DEFAULT" -computername $strComputer | select-object IdentifyingNumber, Displayname, DisplayVersion 
$getWmiClass2 = get-wmiobject -class  "SampleProductsList" -namespace "root\DEFAULT" -computername $strComputer | select-object IdentifyingNumber, Displayname, DisplayVersion 
foreach ($AppDisplayName in $name) {
    $GetWmiClass $GetWmiClass2 | % {
        % ($DispName in $_) {
            if($DispName.DisplayName -eq $AppDisplayName) {
                $classKey += "IdentifyingNumber=`"`{${DispName.IdentifyingNumber}`}`",Name=`"${DispName.Displayname}`",version=`"${DisplayVersion}`""
                ([wmi]"\\$server\root\cimv2:Win32_Product.$classKey").uninstall()
            }
        }
    }
}

我重写了代码(添加了一个过滤器),但它没有帮助。

filter GetApps {
    foreach ($DispName in $_) {
        if($DispName.DisplayName -eq $AppDisplayName) {
            $classKey += "IdentifyingNumber=`"`{${DispName.IdentifyingNumber}`}`",Name=`"${DispName.Displayname}`",version=`"${DisplayVersion}`""
            ([wmi]"\\$server\root\cimv2:Win32_Product.$classKey").uninstall()
        }
    }
}
$name = @("softwareName1", "softwareName2", "softwareName3")
$strComputer = "localhost"
$getWmiClass = get-wmiobject -class "SampleProductsList32" -namespace "root\DEFAULT" -computername $strComputer | select-object IdentifyingNumber, Displayname, DisplayVersion 
$getWmiClass2 = get-wmiobject -class  "SampleProductsList" -namespace "root\DEFAULT" -computername $strComputer | select-object IdentifyingNumber, Displayname, DisplayVersion 
foreach ($AppDisplayName in $name) { $GetWmiClass $GetWmiClass2 | GetApps }

这里出现错误信息:

Unexpected token 'GetWmiClass2' in expression or statement.
At line:2 char:31
+     $GetWmiClass $GetWmiClass2 <<<<  | % {
    + CategoryInfo          : ParserError: (GetWmiClass2:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

1 个答案:

答案 0 :(得分:4)

您期望$GetWmiClass $GetWmiClass2做什么?它不是一个有效的Powershell表达式。

在语句的开头有一个变量$GetWmiClass,所以它必须是一个表达式,因为命令不能与变量一起使用。紧接着是另一个变量,没有中间操作符,因此您会收到意外的令牌错误。

你的意思是:

@($GetWmiClass, $GetWmiClass2 ) | % { ... }

将每个值传递到脚本块?