PowerShell error: "Could not find member" only when executed in if condition

PowerShell error: "Could not find member" only when executed in if condition

用于检查远程计算机上安装了多少更新的简单脚本:

$computername = "remotePC"
$updatesession =  [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session",$computer))
$updatesearcher = $updatesession.CreateUpdateSearcher()
$updatesearcher.gettotalhistorycount()

这个脚本对我来说运行良好。但是,如果我将最后一行用作 if 语句条件,例如:

if($updatesearcher.gettotalhistorycount() = 0){ Write-Verbose "no update entries found"}

我得到一个 MissingMemberException:

"Error while invoking gettotalhistorycount. Could not find member."

我不确定为什么它会在 if 语句中做任何不同的事情。如果我只有 if 条件打印 $updatesearcher:

的成员
if( write-host $($updatesearcher | gm )){}

它列出了 gettotalhistorycount(),但为什么当我尝试执行它时却没有?

您正在尝试分配 0 给那个方法。相反,您不想使用 -eq:

比较
if($updatesearcher.gettotalhistorycount() -eq 0){ Write-Verbose "no update entries found"}