问题描述
我有脚本可以通过 PowerShell 从控制面板卸载 Veeam 软件。在卸载最后一个 Veeam 组件期间,我收到以下错误:
You Cannot call a method on a null-valued expression PowerShell : line 15 char:1
+ $console.Uninstall()
+ CategoryInfo : InvalidOperation: (:) [],RuntimeException
+FullyQualifiedErrorId : InvokeMethodonNull
我不知道,专家帮我解决。我在等你的回复。我在下面附上了我的脚本。
function uninstallvm
{
$veeamConsole = 'Veeam Backup & Replication Console'
$objects = Get-WmiObject -Class win32_product
$veeamComponents = $objects | where {$_.Name -like 'Veeam*' -and $_.Name -ne $veeamConsole}
foreach ($object in $veeamComponents) {
Write-Output "Uninstalling $($object.Name)"
$object.Uninstall()
}
Start-Sleep -Seconds 5
$console = $objects | where {$_.Name -eq $veeamConsole}
Write-Output "Uninstalling $($console.Name)"
$console.Uninstall()
}
uninstallvm
解决方法
您收到该错误的原因是在此之后:
$console = $objects | where {$_.Name -eq $veeamConsole}
您的 $console
变量为 $null
,表示没有找到具有 Name 属性的对象 等于 Veeam备份和复制控制台:
PS /> $null.Uninstall()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $null.Uninstall()
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [],RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
这可以通过在尝试调用 uninstall
方法之前添加条件来轻松解决。
function uninstallvm
{
$veeamConsole = 'Veeam Backup & Replication Console'
$objects = Get-WmiObject -Class win32_product
$veeamComponents = $objects | where {$_.Name -like 'Veeam*' -and $_.Name -ne $veeamConsole}
foreach ($object in $veeamComponents)
{
Write-Output "Uninstalling $($object.Name)"
$object.Uninstall()
}
Start-Sleep -Seconds 5
$console = $objects | where {$_.Name -eq $veeamConsole}
if(-not $console)
{
return "No object found with name: $veeamConsole"
}
Write-Output "Uninstalling $($console.Name)"
$console.Uninstall()
}
uninstallvm