删除软件时“无法在空值表达式上调用方法”错误

时间:2017-04-11 09:33:20

标签: powershell scripting windows-server-2012-r2

我知道这个问题还有其他线程,但它们都涉及我不理解的代码。我对脚本编程知之甚少,而且我正在找人帮助我提供一个易于理解的答案。

我正在尝试使用PowerShell删除程序(该程序没有卸载程序文件)。

我可以使用控制面板→程序和功能删除它,但我想通过PSSession远程执行此操作。因此,在Google上进行一些搜索后,我发现了以下脚本。

我先跑

Get-WmiObject -Class Win32_Product | Select-Object -Property Name

这让我得到了我要删除的程序的名称:“OpenOTP-CP(64位)”

然后我运行脚本:

$app = Get-WmiObject -Class Win32_Product | Where-Object { 
    $_.Name -match "OpenOTP-CP (64 bit)" 
}
$app.Uninstall()

然后我收到以下错误

You cannot call a method on a null-valued expression.
At C:\Users\Administrator\Desktop\Remote2.ps1:4 char:1
+ $app.Uninstall()
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

有人可以通过告诉我有什么问题或者向我提供正确的代码来帮助我吗?

2 个答案:

答案 0 :(得分:1)

听起来write-host "app is: $app"可能是一个空变量。在您致电$app.uninstall()之前,我会先添加一个临时If ($app){ $app.Uninstall() }else{ write-host "app was not found" } 来检查是否属实。

或者,你可以添加一些这样的逻辑:

-match

$ app可能为空的原因是-like运算符使用正则表达式,因此它可能将括号视为特殊字符。尝试使用-match代替$app = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -like "*OpenOTP-CP (64 bit)*" } 并用星号包围它:

truncate table table_xyz

insert into table_aaa

select * from (select * from table_dsd union all select * from table_dsdf)

答案 1 :(得分:0)

您可以这样做,这样会更快。我认为这是一个msi提供程序。

get-package "*OpenOTP-CP (64 bit)*" | uninstall-package