I am having script to uninstall Veeam software from control panel through PowerShell. While during uninstall of last the last Veeam components I am getting below error:

You Cannot call a method on a null-valued expression PowerShell : line 15 char:1
+ $console.Uninstall()
+ CategoryInfo         : InvalidOperation: (:) [], RuntimeException
+FullyQualifiedErrorId : InvokeMethodOnNull

I have no idea, Experts help me to fix it. I am waiting for your reply. I have attached my script below.

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
1

There are 1 best solutions below

3
On

The reason why you're getting that error is because after this:

$console = $objects | where {$_.Name -eq $veeamConsole}

Your $console variable is $null meaning that there was no object found with the Name property equal to Veeam Backup & Replication Console:

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

This could be easily fixed by adding a condition before trying to call the uninstall method.

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