# NOTE: This script will only have an effect Windows 10 Professional and Enterprise versions

# Return a Powershell version object from a string
Function Get-Version {
    param([Parameter(Mandatory=$true)][string]$Version)
    [int]$Sets = 4
    $VersionArray = $Version.Split('.')
    If ( $VersionArray.Count -le $Sets ) { $Sets = $VersionArray.Count }
    For ($i = 0; $i -le ($Sets - 1); $i++) {
        $Return = '{0}.{1}' -f $Return, $VersionArray[$i] }
    Return [version]$Return.Trim('.')
}

# Compare current Windows version with a supplied version
# The value supplied must be a string and must include at least 1 decimal
# Use this page to match build numbers and servicing release versions: https://docs.microsoft.com/en-us/windows/release-health/release-information
Function IsWindowsVersion {
    param(
        [Parameter(Mandatory=$true,ParameterSetName='gt')][string]$gt,
        [Parameter(Mandatory=$true,ParameterSetName='ge')][string]$ge,
        [Parameter(Mandatory=$true,ParameterSetName='lt')][string]$lt,
        [Parameter(Mandatory=$true,ParameterSetName='le')][string]$le,
        [Parameter(Mandatory=$true,ParameterSetName='eq')][string]$eq
    )
    [version]$WindowsVersion = [System.Environment]::OSVersion.Version
    switch ($PSCmdlet.ParameterSetName) {
        'gt' { If ( $WindowsVersion -gt (Get-Version $gt) ) { Return $true } Else { Return $false } }
        'ge' { If ( $WindowsVersion -ge (Get-Version $ge) ) { Return $true } Else { Return $false } }
        'lt' { If ( $WindowsVersion -lt (Get-Version $lt) ) { Return $true } Else { Return $false } }
        'le' { If ( $WindowsVersion -le (Get-Version $le) ) { Return $true } Else { Return $false } }
        'eq' { If ( $WindowsVersion -eq (Get-Version $eq) ) { Return $true } Else { Return $false } }
    }
}

# Make sure we're running at least Windows 10 1803 but not higher than Windows 10 21H2
# This is because the Group Policy setting used below was introduced in 1803, so anything before that won't have any effect
If ( (IsWindowsVersion -ge "10.0.17134") -and (IsWindowsVersion -le "10.0.19045") ) {

    # This is the version of Windows 10 you want to update to, but no further
    $MaxWindowsVersion = "22H2"
    
    $BaseRegPath = "HKLM:SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate"
    If (-not (Test-Path $BaseRegPath) ) { New-Item -Path $BaseRegPath -Force | Out-Null }

    New-ItemProperty -Path $BaseRegPath -Name "ProductVersion" -Value "Windows 10" -PropertyType String -Force | Out-Null
    New-ItemProperty -Path $BaseRegPath -Name "TargetReleaseVersion" -Value 1 -PropertyType DWord -Force | Out-Null
    New-ItemProperty -Path $BaseRegPath -Name "TargetReleaseVersionInfo" -Value "${MaxWindowsVersion}" -PropertyType String -Force | Out-Null

    # Restart the Windows Update service if it's currently running
    If ( $(Get-Service -Name wuauserv).Status -eq "Running" ) { Restart-Service -Name wuauserv -Force -ErrorAction SilentlyContinue }
}
