1
(Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }).Uninstall() | Out-Null

我有以下代码可以完美运行。唯一的问题是我不知道该软件是否已被删除。这并没有告诉我,但下面的代码可以。

这种方式对我有用。

$software = Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }

$soft = $software.Uninstall();
$n = $software.ReturnValue;

if ( $n -eq 0 ){
SOFTWARE HAS BEEN REMOVED.
}

我的问题是我如何判断该软件是否已被删除。使用此代码。

(Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }).Uninstall() | Out-Null
4

1 回答 1

1

您必须检查 ReturnValue 属性。当您通过管道传递给您时,Out-Null您正在抑制操作的输出,并且无法判断发生了什么,除非您发出第二次调用以查找它是否返回有问题的软件。

我建议使用 Filter 参数(而不是使用Where-Object)来查询服务器上的软件。为了安全起见,您还应该将结果通过管道传送到Foreach-Objectcmdlet,您永远不知道由于匹配操作而返回了多少软件对象(并且您调用 Uninstall 方法,就好像结果只是一个对象一样):

Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -Filter "Name LIKE '%$softwareName%'" | Foreach-Object { 

     Write-Host "Uninstalling: $($_.Name)"

     $rv = $_.Uninstall().ReturnValue 

     if($rv -eq 0)
     {
        "$($_.Name) uninstalled successfully"
     }     # Changed this round bracket to a squigly one to prperly close the scriptblock for "if"
     else
     {
        "There was an error ($rv) uninstalling $($_.Name)"
     }
}
于 2011-12-14T12:16:29.817 回答