hello
hello

Reputation: 25

powershell remove software from PC

(Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }).Uninstall() | Out-Null

I have following code which works perfectly. The only problem is that I wont to know if the software has been removed or not.This doesn't tells me but the code below does.

This way works for me.

$software = Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }

$soft = $software.Uninstall();
$n = $software.ReturnValue;

if ( $n -eq 0 ){
SOFTWARE HAS BEEN REMOVED.
}

my question is that how do i tell if the software has been removed or not. using this code.

(Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }).Uninstall() | Out-Null

Upvotes: 1

Views: 3567

Answers (1)

Shay Levy
Shay Levy

Reputation: 126722

You have to check the ReturnValue property. When you pipe to Out-Null you are suppressing the output of the operation and there's no way to tell what happened, unless you issue a second call to find if it returns the software in question.

I recommend using the Filter parameter (instead of using Where-Object) to query the software on the server. To be safe you should also pipe the results to the Foreach-Object cmdlet, you never know how many software objects you get back due to the match operation (and you call the Uninstall method as if the result is one object only):

Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -Filter "Name LIKE '%$softwareName%'" | Foreach-Object { 

     Write-Host "Uninstalling: $($_.Name)"

     $rv = $_.Uninstall().ReturnValue 

     if($rv -eq 0)
     {
        "$($_.Name) uninstalled successfully"
     }     # Changed this round bracket to a squigly one to prperly close the scriptblock for "if"
     else
     {
        "There was an error ($rv) uninstalling $($_.Name)"
     }
}

Upvotes: 1

Related Questions