web-dev-qa-db-ja.com

PowerShellを使用してアプリケーションをアンインストールするにはどうすればよいですか?

PowerShellを使用して既存のアプリケーションをアンインストールする標準の「プログラムの追加と削除」機能にフックする簡単な方法はありますか?または、アプリケーションがインストールされているかどうかを確認するには?

124
Rob Paterson
$app = Get-WmiObject -Class Win32_Product | Where-Object { 
    $_.Name -match "Software Name" 
}

$app.Uninstall()

編集: Robは、Filterパラメーターを使用して別の方法を見つけました。

$app = Get-WmiObject -Class Win32_Product `
                     -Filter "Name = 'Software Name'"
146
Jeff Hillman

Jeff Hillmanの投稿の2番目の方法を修正するには、次のいずれかを実行できます。

$app = Get-WmiObject 
            -Query "SELECT * FROM Win32_Product WHERE Name = 'Software Name'"

または

$app = Get-WmiObject -Class Win32_Product `
                     -Filter "Name = 'Software Name'"
34
Robert Wagner

この投稿に少し追加するには、複数のサーバーからソフトウェアを削除できる必要がありました。私はジェフの答えを使って私をこれに導いた:

最初にサーバーのリストを取得し、 AD クエリを使用しましたが、必要に応じてコンピューター名の配列を指定できます。

$computers = @("computer1", "computer2", "computer3")

次に、それらをループして、-computerパラメーターをgwmiクエリに追加しました。

foreach($server in $computers){
    $app = Get-WmiObject -Class Win32_Product -computer $server | Where-Object {
        $_.IdentifyingNumber -match "5A5F312145AE-0252130-432C34-9D89-1"
    }
    $app.Uninstall()
}

正しいアプリケーションをアンインストールしていることを確認するために、IdentifyingNumberプロパティを使用して、名前の代わりに照合しました。

7
David Stetler

Win32_Productクラスは、修復をトリガーし、クエリが最適化されていないため、推奨されないことがわかりました。 ソース

この投稿 Sitaram Pamarthiから、アプリのGUIDを知っている場合にアンインストールするスクリプトを見つけました。また、アプリを非常に高速に検索する別のスクリプトを提供しています こちら

このように使用します:。\ uninstall.ps1 -GUID {C9E7751E-88ED-36CF-B610-71A1D262E906}

[cmdletbinding()]            

param (            

 [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
 [string]$ComputerName = $env:computername,
 [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
 [string]$AppGUID
)            

 try {
  $returnval = ([WMICLASS]"\\$computerName\ROOT\CIMV2:win32_process").Create("msiexec `/x$AppGUID `/norestart `/qn")
 } catch {
  write-error "Failed to trigger the uninstallation. Review the error message"
  $_
  exit
 }
 switch ($($returnval.returnvalue)){
  0 { "Uninstallation command triggered successfully" }
  2 { "You don't have sufficient permissions to trigger the command on $Computer" }
  3 { "You don't have sufficient permissions to trigger the command on $Computer" }
  8 { "An unknown error has occurred" }
  9 { "Path Not Found" }
  9 { "Invalid Parameter"}
 }
6
Ricardo
function Uninstall-App {
    Write-Output "Uninstalling $($args[0])"
    foreach($obj in Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall") {
        $dname = $obj.GetValue("DisplayName")
        if ($dname -contains $args[0]) {
            $uninstString = $obj.GetValue("UninstallString")
            foreach ($line in $uninstString) {
                $found = $line -match '(\{.+\}).*'
                If ($found) {
                    $appid = $matches[1]
                    Write-Output $appid
                    start-process "msiexec.exe" -arg "/X $appid /qb" -Wait
                }
            }
        }
    }
}

次のように呼び出します:

Uninstall-App "Autodesk Revit DB Link 2019"
5

私は自分の小さな貢献をします。同じコンピューターからパッケージのリストを削除する必要がありました。これが私が思いついたスクリプトです。

$packages = @("package1", "package2", "package3")
foreach($package in $packages){
  $app = Get-WmiObject -Class Win32_Product | Where-Object {
    $_.Name -match "$package"
  }
  $app.Uninstall()
}

これが役に立つことを証明したいと思います。

このスクリプトは彼に基づいているため、このスクリプトの功績はDavid Stetlerにあります。

3
Ben Key

1行のコード:

get-package *notepad* |% { & $_.Meta.Attributes["UninstallString"]}
2

Msiexecを使用したPowerShellスクリプトは次のとおりです。

echo "Getting product code"
$ProductCode = Get-WmiObject win32_product -Filter "Name='Name of my Software in Add Remove Program Window'" | Select-Object -Expand IdentifyingNumber
echo "removing Product"
# Out-Null argument is just for keeping the power Shell command window waiting for msiexec command to finish else it moves to execute the next echo command
& msiexec /x $ProductCode | Out-Null
echo "uninstallation finished"
2
RBT

ジェフヒルマンの回答に基づく:

以下は、profile.ps1に追加するか、現在のPowerShellセッションで定義できる関数です。

# Uninstall a Windows program
function uninstall($programName)
{
    $app = Get-WmiObject -Class Win32_Product -Filter ("Name = '" + $programName + "'")
    if($app -ne $null)
    {
        $app.Uninstall()
    }
    else {
        echo ("Could not find program '" + $programName + "'")
    }
}

Notepad ++ をアンインストールしたいとしましょう。これをPowerShellに入力するだけです。

> uninstall("notepad++")

Get-WmiObjectには時間がかかることがありますので、しばらくお待ちください。

1
Kolob Canyon

つかいます:

function remove-HSsoftware{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,
ValuefromPipeline = $true,
HelpMessage="IdentifyingNumber can be retrieved with `"get-wmiobject -class win32_product`"")]
[ValidatePattern('{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}}')]
[string[]]$ids,
[parameter(Mandatory=$false,
            ValuefromPipeline=$true,
            ValueFromPipelineByPropertyName=$true,
            HelpMessage="Computer name or IP adress to query via WMI")]
[Alias('hostname,CN,computername')]
[string[]]$computers
)
begin {}
process{
    if($computers -eq $null){
    $computers = Get-ADComputer -Filter * | Select dnshostname |%{$_.dnshostname}
    }
    foreach($computer in $computers){
        foreach($id in $ids){
            write-Host "Trying to uninstall sofware with ID ", "$id", "from computer ", "$computer"
            $app = Get-WmiObject -class Win32_Product -Computername "$computer" -Filter "IdentifyingNumber = '$id'"
            $app | Remove-WmiObject

        }
    }
}
end{}}
 remove-hssoftware -ids "{8C299CF3-E529-414E-AKD8-68C23BA4CBE8}","{5A9C53A5-FF48-497D-AB86-1F6418B569B9}","{62092246-CFA2-4452-BEDB-62AC4BCE6C26}"

完全にはテストされていませんが、PowerShell 4で実行されました。

ここに見られるように、PS1ファイルを実行しました。 AD からすべてのシステムを取得し、すべてのシステム上の複数のアプリケーションをアンインストールしようとします。

私は、IdentifyingNumberを使用して、David Stetlersの入力のソフトウェア原因を検索しました。

未検証:

  1. スクリプト内の関数の呼び出しにIDを追加せず、代わりにパラメーターIDでスクリプトを開始します
  2. 複数のコンピューター名でスクリプトを呼び出すnot関数から自動的に取得
  3. パイプからデータを取得する
  4. IPアドレスを使用してシステムに接続する

しないこと:

  1. ソフトウェアが実際に特定のシステムで検出された場合、情報は提供されません。
  2. 削除の失敗または成功に関する情報は提供されません。

Uninstall()を使用できませんでした。 NULLの値を持つ式のメソッドを呼び出すことは不可能であることを伝えるエラーが発生したことを試してみてください。代わりにRemove-WmiObjectを使用しましたが、これは同じことを達成しているようです。

CAUTION:コンピュータ名を指定しないと、Active DirectoryのALLシステムからソフトウェアが削除されます。

0
user3410872

私のプログラムのほとんどでは、この投稿のスクリプトが仕事をしました。しかし、msiexec.exeまたはWin32_Productクラスを使用して削除できないレガシープログラムに直面する必要がありました。 (何らかの理由でexit 0になりましたが、プログラムはまだそこにありました)

私の解決策は、Win32_Processクラスを使用することでした。

nickdnk の助けを借りて、このコマンドはアンインストールexeファイルのパスを取得します:

64ビット:

[array]$unInstallPathReg= gci "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | foreach { gp $_.PSPath } | ? { $_ -match $programName } | select UninstallString

32ビット:

 [array]$unInstallPathReg= gci "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" | foreach { gp $_.PSPath } | ? { $_ -match $programName } | select UninstallString

結果文字列を消去する必要があります。

$uninstallPath = $unInstallPathReg[0].UninstallString
$uninstallPath = $uninstallPath -Replace "msiexec.exe","" -Replace "/I","" -Replace "/X",""
$uninstallPath = $uninstallPath .Trim()

関連するプログラムのアンインストールexeファイルのパスがある場合、次のコマンドを使用できます。

$uninstallResult = (Get-WMIObject -List -Verbose | Where-Object {$_.Name -eq "Win32_Process"}).InvokeMethod("Create","$unInstallPath")

$ uninstallResult-終了コードを取得します。 0は成功です

上記のコマンドはリモートで実行することもできます-invokeコマンドを使用して実行しましたが、引数-computernameを追加しても機能すると考えられます

0
dsaydon