透過powershell遠端卸載軟體

透過powershell遠端卸載軟體

我有一個在家工作的用戶,但他已連接到我們的內部網路。我有一個遠端存取程式(LANDESK),我可以連接到他的系統,但根據我們的辦公室政策,除非登入我的特殊管理員帳戶,否則我無法刪除程式。切換帳戶會斷開該用戶與 VPN 的連接,從而有效地將我踢出他的系統。

因此,作為一個相當熟練的 PowerShell 用戶,我試圖想出一種方法來運行命令,以在他仍然登錄的情況下以我的管理員帳戶執行該軟體的卸載程序。 Windows 10 v1803。如果有幫助的話,軟體是 SSMS 2014。

感謝您的建議。

答案1

在 PowerShell 中,這很容易做到。

下面的腳本區塊將取得電腦名稱、您的使用者名稱和密碼,連接到遠端電腦並按名稱列出所有已安裝的軟體:

$computerName = "SomeComputerName"
$yourAccount = Get-Credential
Invoke-Command -ComputerName $computerName -Credential $yourAccount -ScriptBlock {
    Get-WmiObject Win32_Product | Select Name
}

當您知道要遠端卸載的產品的名稱 - 您可以像這樣執行卸載:

$computerName = "SomeComputerName"
$appName = "AppName"
$yourAccount = Get-Credential
Invoke-Command -ComputerName $computerName -Credential $yourAccount -ScriptBlock {
    Get-WmiObject Win32_product | Where {$_.name -eq $appName} | ForEach {
        $_.Uninstall()
    }
}

在上面的範例中 - 將“SomeComputerName”替換為您要從中卸載的電腦的名稱。

如果您願意,也可以使用以下行讓腳本提示您輸入電腦名稱:

$computerName = Read-Host "Enter Computer Name"

如果您有多台電腦上裝有您想要卸載的相同軟體 - 您還可以定義要使用的電腦陣列並從許多電腦中進行卸載:

$computerNames = @("SomeComputerName1", "SomeComputerName2", "SomeComputerName3")
$appName = "AppName"
$yourAccount = Get-Credential
ForEach ($computerName in $computerNames) {
    Invoke-Command -ComputerName $computerName -Credential $yourAccount -ScriptBlock {
        Get-WmiObject Win32_product | Where {$_.name -eq $appName} | ForEach {
            $_.Uninstall()
        }
    }
}

答案2

如果您建立一個名為「servers.txt」的檔案並將伺服器清單放入其中,您也可以引用 $computerNames,如下所示:

$computerNames = Get-Content "C:\some-directory\servers.txt"
$appName = "AppName"
$yourAccount = Get-Credential
ForEach ($computerName in $computerNames) {
    Invoke-Command -ComputerName $computerName -Credential $yourAccount -ScriptBlock {
        Get-WmiObject Win32_product | Where {$_.name -eq $appName} | ForEach {
            $_.Uninstall()
        }
    }
}

我在生產環境中多次使用過這種方法,它似乎對我有用。在生產環境中完成之前,請務必在非生產環境中進行測試。

相關內容