Public/Update-VcMdtBundle.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
function Update-VcMdtBundle {
    <#
        .EXTERNALHELP VcRedist-help.xml
    #>

    [CmdletBinding(SupportsShouldProcess = $true, HelpURI = "https://vcredist.com/update-vcmdtbundle/")]
    [OutputType([System.Management.Automation.PSObject])]
    param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline)]
        [ValidateScript( { if (Test-Path -Path $_ -PathType 'Container') { $true } else { throw "Cannot find path $_" } })]
        [System.String] $MdtPath,

        [Parameter(Mandatory = $false)]
        [ValidatePattern("^[a-zA-Z0-9]+$")]
        [ValidateNotNullOrEmpty()]
        [System.String] $AppFolder = "VcRedists",

        [Parameter(Mandatory = $false, Position = 1)]
        [ValidatePattern("^[a-zA-Z0-9]+$")]
        [System.String] $MdtDrive = "DS099",

        [Parameter(Mandatory = $false, Position = 2)]
        [ValidatePattern("^[a-zA-Z0-9]+$")]
        [System.String] $Publisher = "Microsoft",

        [Parameter(Mandatory = $false, Position = 3)]
        [ValidatePattern("^[a-zA-Z0-9\+ ]+$")]
        [System.String] $BundleName = "Visual C++ Redistributables"
    )

    begin {
        # Variables
        $Applications = "Applications"
        Write-Warning -Message "Attempting to update bundle: [$Publisher $BundleName]."

        # If running on PowerShell Core, error and exit.
        if (Test-PSCore) {
            Write-Warning -Message "PowerShell Core doesn't support PSSnapins. We can't load the MicrosoftDeploymentToolkit module."
            throw [System.Management.Automation.InvalidPowerShellStateException]
            Exit
        }
    }

    process {
        # Import the MDT module and create a PS drive to MdtPath
        if (Import-MdtModule) {
            if ($PSCmdlet.ShouldProcess($Path, "Mapping")) {
                try {
                    $params = @{
                        Drive       = $MdtDrive
                        Path        = $MdtPath
                        ErrorAction = "SilentlyContinue"
                    }
                    New-MdtDrive @params > $null
                    Restore-MDTPersistentDrive -Force > $null
                }
                catch [System.Exception] {
                    Write-Warning -Message "Failed to map drive to [$MdtPath]."
                    throw $_.Exception.Message
                }
            }
        }
        else {
            Write-Warning -Message "Failed to import the MDT PowerShell module. Please install the MDT Workbench and try again."
            throw [System.Management.Automation.InvalidPowerShellStateException]
        }

        # Get properties from the existing bundle/s
        try {
            $gciParams = @{
                Path        = "$($MdtDrive):\$Applications"
                Recurse     = $true
                ErrorAction = "SilentlyContinue"
            }
            $Bundles = Get-ChildItem @gciParams | Where-Object { $_.Name -eq "$Publisher $BundleName" }
        }
        catch [System.Exception] {
            Write-Warning -Message "Failed to retrieve the existing Visual C++ Redistributables bundle."
            throw $_.Exception.Message
        }

        foreach ($Bundle in $Bundles) {
            Write-Verbose -Message "Found bundle: '$($Bundle.Name)'."

            # Grab the Visual C++ Redistributable application guids; Sort added VcRedists by version so they are ordered correctly
            $target = "$($MdtDrive):\$Applications\$AppFolder"
            Write-Verbose -Message "Gathering VcRedist applications in: $target"
            $existingVcRedists = Get-ChildItem -Path $target | Where-Object { ($_.Name -like "*Visual C++*") -and ($_.guid -ne $bundle.guid) -and ($_.CommandLine -ne "") }
            $existingVcRedists = $existingVcRedists | Sort-Object -Property @{ Expression = { [System.Version]$_.Version }; Descending = $false }
            $dependencies = @(); foreach ($app in $existingVcRedists) { $dependencies += $app.guid }

            if ($PSCmdlet.ShouldProcess($bundle.PSPath, "Update dependencies")) {
                try {
                    $sipParams = @{
                        Path        = ($bundle.PSPath.Replace($bundle.PSProvider, "")).Trim(":")
                        Name        = "Dependency"
                        Value       = $dependencies
                        ErrorAction = "SilentlyContinue"
                        Force       = $true
                    }
                    Set-ItemProperty @sipParams > $null
                }
                catch [System.Exception] {
                    Write-Warning -Message "Error updating VcRedist bundle dependencies."
                    throw $_.Exception.Message
                }
            }
            if ($PSCmdlet.ShouldProcess($bundle.PSPath, "Update version")) {
                try {
                    $sipParams = @{
                        Path        = $($bundle.PSPath.Replace($bundle.PSProvider, "")).Trim(":")
                        Name        = "Version"
                        Value       = $(Get-Date -Format (([System.Globalization.CultureInfo]::CurrentUICulture.DateTimeFormat).ShortDatePattern))
                        ErrorAction = "SilentlyContinue"
                        Force       = $true
                    }
                    Set-ItemProperty @sipParams > $null
                }
                catch [System.Exception] {
                    Write-Warning -Message "Error updating VcRedist bundle version."
                    throw $_.Exception.Message
                }
            }

            # Write the bundle to the pipeline
            Write-Output -InputObject ($bundle | Select-Object -Property * )
        }
    }
}