Отправить команды на удаленный сервер с помощью powershell - PullRequest
0 голосов
/ 10 октября 2019

Я новичок в сценариях powershell

Я хочу удалить программное обеспечение, расположенное на удаленном компьютере, с моего локального компьютера, поэтому я использую

$computer =Read-Host -Prompt 'Input your server name or IP adress'
$user =Read-Host -Prompt 'Input your server username'
Invoke-Command -ComputerName $computer -ScriptBlock {  

Write-host -ForegroundColor Magenta "Please select the software you wish to uninstall..."


    $javaVer = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*", "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select DisplayName, UninstallString, InstallLocation, InstallDate | out-gridview -PassThru



    write-host -ForegroundColor Yellow "The following software will be uninstalled:"




ForEach ($ver in $javaVer) {

    If ($ver.UninstallString) {

        $uninst = $ver.UninstallString
        & cmd /c $uninst /quiet /norestart
    }

}
} -credential $user

, чтобы проверить его на своем локальном компьютере. получил эту ошибку

Out-GridView, не проходящий через сессию с дистанцией. + CategoryInfo: InvalidOperation: (Microsoft.Power ... GridViewCommand: OutGridViewCommand) [Out-GridView], NotSupportedException + FullyQualifiedErrorId: RemotingNotSupported, Microsoft.PowerShell.Commands.OutGridViewCommand * PSComputer * * 101

1010: 1: 1002: 1010: * *1002* 1010: * * * * * 100 * 1010: * * * * * * * * 100 * 1011: * * * * * * * * * * * * 100 * * * 100 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 100Google переведено: *1012*

Out-GridView не работает из удаленного сеанса. + CategoryInfo: InvalidOperation: (Microsoft.Power ... GridViewCommand: OutGridViewCommand) [Out-GridView], NotSupportedException + FullyQualifiedErrorId: RemotingNotSupported, Microsoft.PowerShell.Commands.OutGridViewCommand + PsComputerName: 192.168.1.200

но если я посылаю простую команду типа ipconfig, она работает

Что я делаю не так?

1 Ответ

0 голосов
/ 10 октября 2019

, так как вы НЕ МОЖЕТЕ выполнить Out-GridView в удаленном, неинтерактивном сеансе [что вы получаете из Invoke-Command], это разбивает процесс на шаги ...

  • запрашивает цельимя системы
  • устанавливает два блока сценариев IC
  • получает список удаленно установленных приложений через IC, а 1-й блок сценария
  • показывает, что через O-GV пользователь может выбирать приложения
  • показывает приложения, которые будут удалены
  • выполняет фактическую удаленную деинсталляцию через 2-й вызов IC, используя 2-й блок сценария

, отметьте, что фактическая команда для деинсталляцииприложения были преобразованы в расширенную строку. удалите двойные кавычки вокруг "& cmd /c $uninst /quiet /norestart", когда будете готовы сделать это.

также, нет обработки ошибок вообще. [ ухмылка ]

# the following likely should include a test to see if the system actually exists
$ComputerName = Read-Host -Prompt 'Input your server name or IP adress '
#$user = Read-Host -Prompt 'Input your server username'
Write-Host ''

$ICScriptblock_One = {
    $HKLM_TargetList = @(
        "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*"
        "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
        )
    # send the results to the calling system
    Get-ItemProperty -Path $HKLM_TargetList |
        Where-Object {
            # filter out items with blanks in the follwing properties
            $_.DisplayName -and
            $_.UninstallString
            } |
        Sort-Object -Property DisplayName |
        Select-Object -Property DisplayName, UninstallString, InstallLocation, InstallDate
    } # end >>> $ICScriptblock_One = {

$ICScriptblock_Two = {
    ForEach ($ATR_Item in $Using:AppsToRemove)
        {
        $uninst = $ATR_Item.UninstallString
        # remove the double quotes when ready to do this for real
        "& cmd /c $uninst /quiet /norestart"
        }
    } # end >>> $ICScriptblock_Two = {

$InstalledAppList = Invoke-Command -ComputerName $ComputerName -ScriptBlock $ICScriptblock_One

$OGVMessage = 'Please select the software you wish to uninstall...'
$AppsToRemove = $InstalledAppList |
    Out-GridView -Title $OGVMessage -OutputMode Multiple

write-host -ForegroundColor Yellow "The following software will be uninstalled :"
$AppsToRemove.DisplayName |
    Out-Host
Write-Host ''

Invoke-Command -ComputerName $ComputerName -ScriptBlock $ICScriptblock_Two

вывод на экран ...

Input your server name or IP adress : localhost

The following software will be uninstalled :
Apple Software Update
Google Update Helper
Python 3.7.4 Utility Scripts (64-bit)
Speccy

& cmd /c MsiExec.exe /I{A30EA700-5515-48F0-88B0-9E99DC356B88} /quiet /norestart
& cmd /c MsiExec.exe /I{60EC980A-BDA2-4CB6-A427-B07A5498B4CA} /quiet /norestart
& cmd /c MsiExec.exe /I{16F74529-EDE0-4BBD-B2AF-89AF9C696EA8} /quiet /norestart
& cmd /c "C:\Program Files\Speccy\uninst.exe" /quiet /norestart
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...