Pages

Friday, 12 January 2024

PowerShell script to Auto upgrade the applications through winget

 $apps = @(

    "7zip.7zip",
    "Notepad++.Notepad++",
    "Google.Chrome",
    "WiresharkFoundation.Wireshark",
    "VideoLAN.VLC",
    "PuTTY.PuTTY",
    "Microsoft.PowerToys",
    "Zoom.Zoom",
    "Apple.iTunes",
    "Autodesk.AutodeskAccess"
)
$logPath = "C:\Windows\Logs\Software\WingetList"  # Log files folder
$logFile = Join-Path $logPath "Updates.txt"    ## Upgrade required applications will be stored here
$str_LogFile = Join-Path $logPath "WInget_Install.log"  ##This is for Winget application Install

# Ensure the log directory exists
if (!(Test-Path $logPath)) {
    New-Item -Path $logPath -ItemType Directory
}
If (test-path $logFile){
Remove-Item $logFile -Force
}

    #Check Winget Install
    Write-Host "Checking if Winget is installed" -ForegroundColor Yellow
    $TestWinget = Get-AppxProvisionedPackage -Online | Where-Object {$_.DisplayName -eq "Microsoft.DesktopAppInstaller"}
    If ([Version]$TestWinGet. Version -gt "2022.506.16.0")
    {
        Write-Host "WinGet is Installed" -ForegroundColor Green

  #  Add-Content $str_LogFile "WinGet is Installed"
    }Else
        {

        #temp folder
        $InstallerFolder = $(Join-Path $env:ProgramData WIngetInstall)
        if (!(Test-Path $InstallerFolder))
        {
        New-Item -Path $InstallerFolder -ItemType Directory -Force -Confirm:$false
        }

        #Download WinGet MSIXBundle

        Add-Content $str_LogFile "Not installed. Downloading WinGet..."
        Write-Host "Not installed. Downloading WinGet..."
        $WinGetURL = "https://aka.ms/getwinget"
        (New-Object System.Net.WebClient).DownloadFile($WinGetURL, "$InstallerFolder\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle")
        #Install WinGet MSIXBundle
        Try     {
             Add-Content $str_LogFile "Installing MSIXBundle for App Installer..."
           
            Add-AppxProvisionedPackage -Online -PackagePath "$InstallerFolder\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -SkipLicense
            Write-Host "Installed MSIXBundle for App Installer" -ForegroundColor Green
              Add-Content $str_LogFile "Installed MSIXBundle for App Installer"
            }
        Catch {
            Write-Host "Failed to install MSIXBundle for App Installer..." -ForegroundColor Red

             Add-Content $str_LogFile "Failed to install MSIXBundle for App Installer..."
            }
   
        Start-Sleep -Seconds 30
       
        #Remove WinGet MSIXBundle
        Remove-Item -Path "$InstallerFolder\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -Force -ErrorAction Continue
        }



$ResolveWingetPath = Resolve-Path "C:\Program Files\WindowsApps\Microsoft.DesktopAppInstaller_*_x64__8wekyb3d8bbwe"

if ($ResolveWingetPath) {
    $WingetPath = $ResolveWingetPath[-1].Path

    # Set location to the resolved Winget path
    Set-Location $WingetPath

    $appsToUpdate = @()

    foreach ($app in $apps) {
        $lines = .\winget.exe list --Id $app
        if ($lines -match '\bVersion\s+Available\b') {
            $appsToUpdate += $app
        }
    }

    if ($appsToUpdate.Count -gt 0) {
        # Log the apps with available updates to the file
        $appsToUpdate | Out-File -Append -FilePath $logFile

        Write-Host "Updates available for the following apps:"
        $appsToUpdate | ForEach-Object { Write-Host "- $_" }
        exit 1

    } else {
        Write-Host "No updates available for the specified apps."

        exit 0
    }
} else {
    Write-Error "Winget path not resolved. Ensure that the path is correct and the application is installed."
}

#########################################################################################################################################


Remediation Script :


#####################################################################################################################################
##Constants
$logPath = "C:\Windows\Logs\Software\WingetLogs"
$input = "C:\Windows\Logs\Software\WingetList\Updates.txt"  # App install list input file
$logFile = Join-Path $logPath "wingetLog_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"

#####################################################################################################################################
$apps = get-content $input  #We are getting the apps from the Updates.txt file


foreach ($app in $apps) {
    # Check if the application is Notepad++ and kill its process if it's running
    if ($app -eq 'Notepad++.Notepad++') {
        $notepadProcesses = Get-Process -Name 'notepad++' -ErrorAction SilentlyContinue
        if ($notepadProcesses) {
            Write-Host "Killing Notepad++ processes..."
            Stop-Process -Name 'notepad++' -Force
        }
    }

    }

# Ensure the log directory exists
if (!(Test-Path $logPath)) {
    New-Item -Path $logPath -ItemType Directory
   
}

# Cleanup old log files (older than a week)
$oldLogs = Get-ChildItem -Path $logPath -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) }
foreach ($oldLog in $oldLogs) {
    Remove-Item $oldLog.FullName -Force
}

$ResolveWingetPath = Resolve-Path "C:\Program Files\WindowsApps\Microsoft.DesktopAppInstaller_*_x64__8wekyb3d8bbwe"

if ($ResolveWingetPath) {
    $WingetPath = $ResolveWingetPath[-1].Path

    # Set location to the resolved Winget path
    Set-Location $WingetPath

    foreach ($app in $apps) {
        $lines = .\winget.exe list --Id $app
        if ($lines -match '\bVersion\s+Available\b') {
            $verInstalled, $verAvailable = (-split $lines[-1])[-3,-2]
            $upgradeCommand = ".\winget.exe upgrade --exact --id $app --silent --accept-package-agreements --accept-source-agreements --scope machine"

            $logEntry = [PSCustomObject]@{
                Time = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
                Name = $app
                InstalledVersion = [version]$verInstalled
                AvailableVersion = [version]$verAvailable
                UpgradeCommand = $upgradeCommand
            }

            # Log the version information to a file
            $logEntry | Out-File -Append -FilePath $logFile

            # Output log entry to console
            $logEntry | Format-Table -AutoSize

            # Run the upgrade command
            Invoke-Expression $upgradeCommand
        }
        elseif ($lines -match '\bVersion\b'){
         $verInstalled = (-split $lines[-1])[-2]

            $noUpgradeInfo = "Latest version of $app $verInstalled already installed on the machine."
            Write-Verbose -Verbose $noUpgradeInfo

            # Log the information about no available upgrade to a file
            $noUpgradeInfo | Out-File -Append -FilePath $logFile
        }
    }

    Write-Host "Log file created: $logFile"
} else {
    Write-Error "Winget path not resolved. Ensure that the path is correct and the application is installed."
}

No comments:

Post a Comment

User based detection

function getloggedindetails () {     ##Find logged in username     $user = Get-WmiObject Win32_Process - Filter "Name='explorer...

Search This Blog