functions/Invoke-ChocoRemoteUpgrade.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<#
.SYNOPSIS
    Short description
.DESCRIPTION
    Long description
.EXAMPLE
    Example of how to use this cmdlet
.EXAMPLE
    Another example of how to use this cmdlet
#>

function Invoke-ChocoRemoteUpgrade {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string[]]$ComputerName,
        [pscredential]$Credential,
        [string[]]$AdditionalPackages,
        [string[]]$ExcludedPackages,
        [switch]$RebootifPending
    )
    process {
        #Create dynamic upgrade list
    Invoke-Command -ArgumentList $AdditionalPackages,$ExcludedPackages,$ScriptPath,$Credential -ComputerName $ComputerName -ScriptBlock {
        param (
            $AdditionalPackages,
            $ExcludedPackages,
            $ScriptPath
        )
        $packages = [System.Collections.ArrayList]@(choco outdated -r --ignore-unfound --ignore-pinned  | Foreach-Object {
                ($_.split("|"))[0]
        })
        if ($AdditionalPackages){
            foreach ($AddedPackage in $AdditionalPackages){
                if ($packages -notcontains $AddedPackage){
                    $packages.Add($AddedPackage) | Out-Null
                }
            }
        }
        if ($ExcludedPackages){
            foreach ($ExcludedPackage in $ExcludedPackages){
                if ($packages -contains $ExcludedPackage){
                    $packages.Remove($ExcludedPackage) | Out-Null
                }
            }
        }
        foreach ($package in $packages){
            choco upgrade $package -r -y --timeout=600 | Out-File ("c:\Windows\Temp\choco-" + $package + ".txt")
            if ($LASTEXITCODE -ne 0){
                $Result = 'Failed'
            }
            else{
                $Result = 'Success'
            }
            [PSCustomObject]@{
                Name = $Package
                Result = $Result
                Computer = $Env:COMPUTERNAME
            }
        }
    }
    #Restart machines with pending Reboot
    if ($RebootifPending){
        Test-PendingReboot -ComputerName $ComputerName -SkipConfigurationManagerClientCheck | Where-Object {$_.IsRebootpending -eq $True } | ForEach-Object {
            "Rebooting $($_.ComputerName)"
            Restart-Computer -ComputerName $_.ComputerName -Force
        }
    }
   }
}