简体   繁体   中英

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.

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

You should be using Invoke-Command , not Enter-PSSession . The latter is for interactively working in another machine. The former is for running a command in the other machine and getting back results (if any).

Basically, your try block should look like this:

Try {
    Invoke-Command -ComputerName $c -ScriptBlock { msiexec.exe /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}' }
}

If you want more detailed control and error information, consider using WMI to uninstall the product instead of shelling out to msiexec .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM