AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / server / Perguntas / 1174342
Accepted
calqium
calqium
Asked: 2025-03-06 01:17:28 +0800 CST2025-03-06 01:17:28 +0800 CST 2025-03-06 01:17:28 +0800 CST

O script para atualizar aplicativos pelo WinGet não está sendo executado pelo GPO

  • 772

Escrevi o seguinte script no PowerShell para atualizar aplicativos por meio do WinGet e forçar a desinstalação e reinstalação caso a atualização falhe:

<#
.SYNOPSIS
    Installs the Powershell WinGet client module.
.DESCRIPTION
    Checks to see if the Powershell WinGet client module is installed. If not, attempts to install it.
    If the install fails, exits the program.
.NOTES
    The module can be found here: https://www.powershellgallery.com/packages/Microsoft.WinGet.Client/1.10.320.
#>
function Install-WinGetClientModule {
    # Check if official Powershell WinGet client is installed.
    if (Get-Module -ListAvailable -Name Microsoft.WinGet.Client) {
        Write-Host "Powershell Module for the Windows Package Manager Client is installed."
    } else {
        # Install NuGet package provider, which is a requirement to install the module.
        Write-Host "Installing NuGet..."
        Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force

        # Check if the NuGet installed successfully.
        if ($?) {
            Write-Host "Successfully installed." -ForegroundColor Green
        } else {
            # If install could not be completed, exit script.
            Write-Host "Could not install NuGet." -ForegroundColor Red
            exit
        }

        # Set PSGallery as a trusted repository to install from.
        Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted

        # Install the module.
        Write-Host "Installing the Powershell Module for the Windows Package Manager Client..."
        Install-Module -Name Microsoft.WinGet.Client

        # Check if the module installed successfully.
        if ($?) {
            Write-Host "Successfully installed." -ForegroundColor Green
        } else {
            # If install could not be completed, exit script.
            Write-Host "Could not install the Powershell Module for the Windows Package Manager Client." -ForegroundColor Red
            exit
        }
    }
}


<#
.SYNOPSIS
    Get WinGet applications that require updates.
#>
function Get-ApplicationsWithUpdates {
    # Store the applications with updates available through WinGet
    $applicationsWithUpdates = Get-WinGetPackage | Where-Object IsUpdateAvailable

    return $applicationsWithUpdates
}

<#
.SYNOPSIS
    Update applications though WinGet.
#>
function Update-Applications {
    param (
        [Parameter(Mandatory = $true)]
        [Array]$applicationsToUpdate
    )
    
    # Update each application provided.
    foreach ($app in $applicationsToUpdate) {
        $appName = $app.Name
        $appId = $app.Id
        Write-Host "Updating $appName..."
        
        # Update the application
        winget upgrade --id $appId --accept-package-agreements --accept-source-agreements
        
        # Check if the application was successfully updated.
        if ($?) {
            Write-Host "$appName updated to the latest version." -ForegroundColor Green
        } else {
            # If the update failed, attempt to reinstall.
            Write-Host "Failed to update $appName. Attempting to reinstall..."
            winget uninstall --id $appId --silent --accept-source-agreements
            winget install --id $appId --accept-package-agreements --accept-source-agreements

            # Check if the application reinstalled successfully.
            if ($?) {
                Write-Host "$appName updated to the latest version." -ForegroundColor Green
            } else {
                Write-Host "Failed to update $appName." -ForegroundColor Red
            }
        }
    }
}


function Main {
    # Get Powershell WinGet client.
    Install-WinGetClientModule

    # Check for application updates through WinGet.
    $applicationsToUpdate = Get-ApplicationsWithUpdates
    Write-Host $applicationsToUpdate

    # Check that the number of applications to update isn't 0.
    if ($applicationsToUpdate.Count -gt 0) {
        # Update applications.
        Update-Applications -ApplicationsToUpdate $applicationsToUpdate
    } else {
        Write-Host "All applications are up to date."
    } 
}


# Run the script.
Main

Quando eu o executo manualmente pelo terminal, ele funciona como esperado. No entanto, ele não funciona como um script de inicialização de Política de Grupo em Computer Configuration\Policies\Windows Settings\Scripts(Startup/Shutdown).

Ativei a Execução de Script Computer Configuration\Policies\Administrative Templates\Windows Components\Windows Powershelldefinindo a Política de Execução como "Permitir todos os scripts" (isso é apenas para teste e não é implantado para todos os usuários).

Tenho testado para ver se o script funciona instalando versões mais antigas de programas via WinGet, forçando gpupdate, reiniciando o computador e esperando mais de 5 minutos para permitir que o script seja executado de forma assíncrona. Até agora, não tive sorte em fazer o script ser executado.

Há algo que esteja faltando para que este script funcione na inicialização?

windows
  • 1 1 respostas
  • 75 Views

1 respostas

  • Voted
  1. Best Answer
    calqium
    2025-03-10T21:01:56+08:002025-03-10T21:01:56+08:00

    Acontece que o problema não era com a Group Policy, mas com o script. Havia dois problemas:

    Os comandos WinGet não estão disponíveis no contexto do sistema: https://github.com/microsoft/winget-cli/issues/3049

    O módulo cliente Powershell WinGet deve ser executado no Powershell 7, e os scripts de inicialização são executados no Powershell 5.1 por padrão: https://github.com/microsoft/winget-cli/issues/4820

    Corrigi isso criando um script auxiliar para baixar o Powershell 7 e então iniciar o primeiro script usando-o:

    # Check if Powershell version 7 exists
    $powershellSevenPath = "C:\Program Files\PowerShell\7\pwsh.exe"
    $powershellSeven = Test-Path -Path $powershellSevenPath
    
    if (!$powershellSeven) {
        # If it doesn't exist, install it.
        msiexec.exe /package PowerShell-7.5.0-win-x64.msi /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ADD_FILE_CONTEXT_MENU_RUNPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1 USE_MU=1 ENABLE_MU=1 ADD_PATH=1
    }
    
    # Run script with Powershell 7.
    Start-Process -FilePath $powershellSevenPath -Verb RunAs -ArgumentList ".\Update-WinGet-Applications.ps1"
    

    Também tive que alterar todos os comandos WinGet no script original para usar o WinGet Client Module:

    <#
    .SYNOPSIS
        Installs the Powershell WinGet client module.
    .DESCRIPTION
        Checks to see if the Powershell WinGet client module is installed. If it isn't, attempts to install it.
        If the install fails, exits the program.
    .NOTES
        The module can be found here: https://www.powershellgallery.com/packages/Microsoft.WinGet.Client/1.10.320.
    #>
    function Install-WinGetClientModule {
        # Check if official Powershell WinGet client is installed.
        if (Get-Module -ListAvailable -Name Microsoft.WinGet.Client) {
            Write-Host "Powershell Module for the Windows Package Manager Client is installed."
    
        } else {
            # Install NuGet package provider, which is a requirement to install the module.
            Write-Host "Installing NuGet..."
            Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
    
            # Check if NuGet installed successfully.
            if ($?) {
                Write-Host "Successfully installed." -ForegroundColor Green
            } else {
                # If install could not be completed, exit script.
                Write-Host "Could not install NuGet." -ForegroundColor Red
                exit
            }
    
            # Set PSGallery as a trusted repository to install from.
            Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
    
            # Install the module.
            Write-Host "Installing the Powershell Module for the Windows Package Manager Client..."
            Install-Module -Name Microsoft.WinGet.Client
    
            # Check if the module installed successfully.
            if ($?) {
                Write-Host "Successfully installed." -ForegroundColor Green
            } else {
                # If install could not be completed, exit script.
                Write-Host "Could not install the Powershell Module for the Windows Package Manager Client." -ForegroundColor Red
                exit
            }
        }
    }
    
    
    <#
    .SYNOPSIS
        Get WinGet applications that require updates.
    #>
    function Get-ApplicationsWithUpdates {
        # Store the applications with updates available through WinGet
        $applicationsWithUpdates = Get-WinGetPackage | Where-Object IsUpdateAvailable
    
        return $applicationsWithUpdates
    }
    
    
    <#
    .SYNOPSIS
        Update applications though WinGet.
    #>
    function Update-Applications {
        param (
            [Parameter(Mandatory = $true)]
            [Array]$applicationsToUpdate
        )
        
        # Update each application provided.
        foreach ($app in $applicationsToUpdate) {
            $appName = $app.Name
            $appId = $app.Id
            Write-Host "Updating $appName..."
            
            # Update the application
            Update-WinGetPackage -Id $appId -Scope Any -Mode Silent -Force
            
            # Check if the application was successfully updated.
            if ($?) {
                Write-Host "$appName updated to the latest version." -ForegroundColor Green
            } else {
                # If the update failed, attempt to reinstall.
                Write-Host "Failed to update $appName. Attempting to reinstall..."
                Uninstall-WinGetPackage -Id $appId  -Scope Any -Mode Silent -Force
                Install-WinGetPackage -Id $appId  -Scope Any -Mode Silent -Force
    
                # Check if the application reinstalled successfully.
                if ($?) {
                    Write-Host "$appName updated to the latest version." -ForegroundColor Green
                } else {
                    Write-Host "Failed to update $appName." -ForegroundColor Red
                }
            }
        }
    }
    
    
    function Main {
        # Start logging.
        $logDate = Get-Date -Format FileDateTime
        Start-Transcript -Path C:\Users\$env:USERNAME\Documents\Update-WinGetApplicationsLogs\log-$logDate.txt
    
        # Get Powershell WinGet client.
        Install-WinGetClientModule
    
        # Check for application updates through WinGet.
        $applicationsToUpdate = Get-ApplicationsWithUpdates
        Write-Host $applicationsToUpdate
    
        # Check that the number of applications to update isn't 0.
        if ($applicationsToUpdate.Count -gt 0) {
            # Update applications.
            Update-Applications -ApplicationsToUpdate $applicationsToUpdate
        } else {
            Write-Host "All applications are up to date."
        } 
    
        # Stop logging.
        Stop-Transcript
    }
    
    
    # Run the script.
    Main
    
    • 0

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Você pode passar usuário/passar para autenticação básica HTTP em parâmetros de URL?

    • 5 respostas
  • Marko Smith

    Ping uma porta específica

    • 18 respostas
  • Marko Smith

    Verifique se a porta está aberta ou fechada em um servidor Linux?

    • 7 respostas
  • Marko Smith

    Como automatizar o login SSH com senha?

    • 10 respostas
  • Marko Smith

    Como posso dizer ao Git para Windows onde encontrar minha chave RSA privada?

    • 30 respostas
  • Marko Smith

    Qual é o nome de usuário/senha de superusuário padrão para postgres após uma nova instalação?

    • 5 respostas
  • Marko Smith

    Qual porta o SFTP usa?

    • 6 respostas
  • Marko Smith

    Linha de comando para listar usuários em um grupo do Windows Active Directory?

    • 9 respostas
  • Marko Smith

    O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL?

    • 3 respostas
  • Marko Smith

    Como determinar se uma variável bash está vazia?

    • 15 respostas
  • Martin Hope
    Davie Ping uma porta específica 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    kernel O scp pode copiar diretórios recursivamente? 2011-04-29 20:24:45 +0800 CST
  • Martin Hope
    Robert ssh retorna "Proprietário incorreto ou permissões em ~/.ssh/config" 2011-03-30 10:15:48 +0800 CST
  • Martin Hope
    Eonil Como automatizar o login SSH com senha? 2011-03-02 03:07:12 +0800 CST
  • Martin Hope
    gunwin Como lidar com um servidor comprometido? 2011-01-03 13:31:27 +0800 CST
  • Martin Hope
    Tom Feiner Como posso classificar a saída du -h por tamanho 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent Como determinar se uma variável bash está vazia? 2009-05-13 09:54:48 +0800 CST

Hot tag

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve