Search code examples
javapowershellinvoke-command

Using Powershell invoke-expression to uninstall Java on all domain computers


I can ps-session to a remote machine, run the following, and successfully uninstall Java: invoke-expression "msiexec /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}' "

I am trying to create a script that will uninstall from all domain computers:

Import-Module ActiveDirectory
function uninstallJava {
$badcomp = @()
$CompList = Get-ADComputer -Filter 'name -like "*"' | select -ExpandProperty Name
foreach ($c in $CompList) {

Try {
Enter-PSSession -ComputerName $computer 
Invoke-expression "msiexec.exe /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}' "
}

Catch {
$badcomp += $c
}

}

}
uninstallJava
"the following servers could not be reached:"
$badcomp

I don't receive any errors, but it doesn't uninstall Java from the remote machines.

Any ideas appreciated.


Solution

  • Import-Module ActiveDirectory
    $badcomp = @()
    
    Function uninstallJava {
        $CompList = Get-ADComputer -Filter 'name -like "*"' | Select -ExpandProperty Name
        ForEach ($c In $CompList) {
            Try {
                Invoke-Command -ComputerName $c {
                    C:\Windows\System32\cmd.exe /C msiexec.exe /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}'
                }
            } Catch {
                $badcomp += $c
            }
        }
    }
    uninstallJava
    
    Write-Host "the following servers could not be reached:"
    $badcomp