Search code examples
pythonpowershelluninstallstring

Attempting to Silently Uninstall Python, but I get the error "You cannot call a method on a null-valued expression."


I am trying to push an uninstallation script org wide to remove python. Because this is happening on the backend, I need it to uninstall silently. What am I doing wrong? Thanks for any help in advance.

    $Programs = $SearchList | ?{$_.DisplayName -match ($ProgramName -join "|")}
Write-Output "Programs Found: $($Programs.DisplayName -join ", ")`n`n"

Foreach ($Program in $Programs)
{
If (Test-Path $Program.PSPath)
{
Write-Output "Registry Path: $($Program.PSPath | Convert-Path)"
Write-Output "Installed Location: $($Program.InstallLocation)"
Write-Output "Program: $($Program.DisplayName)"
Write-Output "Uninstall Command: $($Program.UninstallString)"

$UninstallString = $_.GetValue('UninstallString')
$isExeOnly = Test-Path -LiteralPath $UninstallString
if ($isExeOnly)
{
$UninstallString = "'$UninstallString'"
}
$UninstallString += '/quiet'

$Uninstall = (Start-Process cmd.exe -ArgumentList '/c', $Program.UninstallString -Wait -PassThru) 
<#Runs the uninstall command located in the uninstall string of the program's uninstall registry key, this is the command that is ran when you uninstall from Control Panel.
If the uninstall string doesn't contain the correct command and parameters for silent uninstallation, then when PDQ Deploy runs it, it may hang, most likely due to a popup.#>

Solution

  • There are several problems:

    • You're mistakenly referring to $_ instead of $Program in $_.GetValue('UninstallString'), which is likely what caused the error you saw.

      • However, $Program.GetValue('UninstallString') also doesn't work, because (as you state it in a later comment) $Program is of type [pscustomobject], which doesn't have a method by that name.

      • If you obtained $Program via Get-ItemProperty (without restricting the result to specific values with -Name), you can access the UninstallString value data as follows:

        $Program.UninstallString
        
    • $UninstallString = "'$UninstallString'" should be
      $UninstallString = "`"$UninstallString`"", because cmd.exe only understands "..." quoting.

    • $UninstallString += '/quiet' should be $UninstallString += ' /quiet', i.e. you need a space before /quiet.

    • You're not using $UninstallString in your Start-Process call.