param([string]$UpdateDirectory)

## They friendly version of Revit we're updating
$RevitVersion = "2020"

## The exact version of Revit we need to compare against
$UpdateVersion = Get-Version "20.2.20.31"

## Registry key to find the existing version of Revit to update
$RegKey = "HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Revit ${RevitVersion}"

## Make sure Revit is installed
If ( Test-Path $RegKey )
{
    ## Make sure the directory with the updates exists
    If ( Test-Path $UpdateDirectory )
    {
        ## Make sure Revit isn't currently running
        $RevitClosed = $true
        Get-Process | Where { $_.Name -like "Revit" } | Select-Object -ExpandProperty Path | ForEach-Object { If ( $_ -match $RevitVersion ) { $RevitClosed = $false } }

        If ( $RevitClosed )
        {
            ## Get the existing Revit version number
            $ExistingVersion = Get-Version $(Get-ItemProperty -Path $RegKey -ErrorAction Stop).DisplayVersion

            If ( $ExistingVersion -lt $UpdateVersion )
            {
                ## Install MSI packages
                Get-ChildItem -Path $UpdateDirectory -Filter *.msi | ForEach-Object {
                    $msi = $_.FullName
                    Write-Output "Installing ${msi}"
                    Try  { Start-Process "msiexec.exe" -ArgumentList "/i ""${msi}"" /qn /norestart" -Wait }
    	            Catch { Write-Output $_.Exception.Message }
                }
                ## Install MSP updates
                Get-ChildItem -Path $UpdateDirectory -Filter *.msp | ForEach-Object {
                    $msp = $_.FullName
                    Write-Output "Installing ${msp}"
                    Try  { Start-Process "msiexec.exe" -ArgumentList "/update ""${msp}"" /qn /norestart" -Wait }
    	            Catch { Write-Output $_.Exception.Message }
                }
            }
            Else { Write-Output "Revit ${RevitVersion} is already up-to-date" }
        }
        Else { Write-Output "Revit ${RevitVersion} is currently running and will not be updated" }
    }
    Else { Write-Output "The specified directory does not exist: ${UpdateDirectory}" }
}
Else { Write-Output "Revit ${RevitVersion} is not installed" }
