Back to the template catalog

Win32 Apps

PuTTY - [IHD]

Starter-pack WinGet template for PuTTY Win32 packaging.

Template details

Category
Win32 Apps
Platform
Windows
Policy type
Windows app (Win32)
Source
Intune Hydration Kit
Subcategory
WinGet catalog app
File path
publicundefined

What this template configures

17 configured properties. Nested values use dotted paths.

packageIdentifier
PuTTY.PuTTY
packageFileName
putty.intunewin
publisher
Simon Tatham
developer
Simon Tatham
notes
Imported from WinGet WinGetPackageIdentifier: PuTTY.PuTTY WinGetPackageVersion: latest WinGetTemplateId: putty WinGetManifestRepository: microsoft/winget-pkgs WinGetManifestPath: manifests/p/PuTTY/PuTTY
setupFilePath
Install-WinGetPackage.ps1
installCommandLine
powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File .\Install-WinGetPackage.ps1
uninstallCommandLine
powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File .\Uninstall-WinGetPackage.ps1
minimumSupportedOperatingSystem.v10_21H1
true
applicableArchitectures
x64
allowAvailableUninstall
true
winget.packageIdentifier
PuTTY.PuTTY
winget.displayName
PuTTY
winget.publisher
Simon Tatham
winget.manifestPath
manifests/p/PuTTY/PuTTY
catalogSubcategory
WinGet catalog app
optIn
true

Available versions

These versions of PuTTY.PuTTY come from the WinGet manifest repository (microsoft/winget-pkgs). A scheduled job updates this list. The list shows only versions that have installer URLs that resolve.

  • Latest is the newest version with installers that resolve.
  • Best effort is an older version. The vendor can remove or replace the download of an older version at any time. If this occurs, the install fails.

In the wizard (create mode), the app installs the latest version, or a version that you select. Only a version with a machine-scope x64 installer can be selected, because the app installs with --scope machine on x64. A selected version uses detection this version or newer: a device that has the selected version or a newer version shows as installed. Thus Intune does not report a failure when the app updates itself.

WinGet versions of PuTTY
VersionStatusReleasedArchitecturesInstaller typesCan be selected
0.85.0.0Latest2026-08-14arm64, x64, x86wix, zipYes
0.84.0.0Best effort2026-05-22arm64, x64, x86wix, zipYes
0.83.0.0Best effort2025-02-08arm64, x64, x86wixYes
0.82.0.0Best effort2024-11-27arm64, x64, x86wixYes
0.81.0.0Best effortNot statedarm64, x64, x86wixYes

Wrapper scripts

Detection script

$PackageIdentifier = 'PuTTY.PuTTY'
$PackageIdentifierPattern = 'PuTTY\.PuTTY'
$DisplayName = 'PuTTY'
$Publisher = 'Simon Tatham'


function Write-WinGetDetectionLog {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Message,


        [Parameter()]
        [ValidateSet('INFO', 'WARN', 'ERROR')]
        [string]$Level = 'INFO'
    )


    Write-Verbose "[$Level] $Message"
}


function Get-WinGetExecutablePath {
    [CmdletBinding()]
    param()


    $programDataRoot = if ([string]::IsNullOrWhiteSpace($env:ProgramData)) { 'C:\ProgramData' } else { $env:ProgramData }
    $programDataWingetRoot = Join-Path -Path $programDataRoot -ChildPath 'Microsoft.DesktopAppInstaller'
    $programDataWingetExe = Join-Path -Path $programDataWingetRoot -ChildPath 'winget.exe'
    $isSystem = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -eq 'NT AUTHORITY\SYSTEM'


    function Test-WinGetExecutable {
        param(
            [Parameter(Mandatory)]
            [string]$Path
        )


        if (-not (Test-Path -Path $Path -PathType Leaf)) {
            return $false
        }


        try {
            $versionOutput = & $Path --version 2>&1
            return $LASTEXITCODE -eq 0 -or $versionOutput -match 'v?\d+\.\d+'
        } catch {
            return $false
        }
    }


    function Get-UserWinGetExecutablePath {
        [CmdletBinding()]
        param()


        $command = Get-Command -Name 'winget.exe' -ErrorAction SilentlyContinue
        if ($command -and -not [string]::IsNullOrWhiteSpace($command.Source) -and (Test-WinGetExecutable -Path $command.Source)) {
            return $command.Source
        }


        $searchPatterns = [System.Collections.Generic.List[string]]::new()


        if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
            $searchPatterns.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\WindowsApps\winget.exe'))
        }


        if (-not [string]::IsNullOrWhiteSpace($env:ProgramFiles)) {
            $searchPatterns.Add((Join-Path -Path $env:ProgramFiles -ChildPath 'WindowsApps\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\winget.exe'))
        }


        if (-not [string]::IsNullOrWhiteSpace(${env:ProgramFiles(x86)})) {
            $searchPatterns.Add((Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'WindowsApps\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\winget.exe'))
        }


        foreach ($pattern in $searchPatterns) {
            if ([string]::IsNullOrWhiteSpace($pattern)) {
                continue
            }


            $candidateFiles = @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | Sort-Object -Property FullName -Descending)
            if ($candidateFiles.Count -gt 0 -and (Test-WinGetExecutable -Path $candidateFiles[0].FullName)) {
                return $candidateFiles[0].FullName
            }
        }


        return $null
    }


    if (-not $isSystem) {
        $userWingetExe = Get-UserWinGetExecutablePath
        if (-not [string]::IsNullOrWhiteSpace($userWingetExe)) {
            return $userWingetExe
        }


        if (Test-WinGetExecutable -Path $programDataWingetExe) {
            return $programDataWingetExe
        }


        return $null
    }


    if (Test-WinGetExecutable -Path $programDataWingetExe) {
        return $programDataWingetExe
    }


    return $null
}


function Test-InstalledApplicationRegistry {
    [CmdletBinding()]
    param()


    function Test-ApplicationPublisher {
        [CmdletBinding()]
        param(
            [Parameter()]
            [string]$InstalledPublisher
        )


        if ([string]::IsNullOrWhiteSpace($Publisher)) {
            return $true
        }


        if ([string]::IsNullOrWhiteSpace($InstalledPublisher)) {
            return $false
        }


        return $InstalledPublisher.IndexOf($Publisher, [System.StringComparison]::OrdinalIgnoreCase) -ge 0
    }


    function Test-ApplicationDisplayName {
        [CmdletBinding()]
        param(
            [Parameter(Mandatory)]
            [string]$InstalledDisplayName
        )


        $namePatterns = @($PackageIdentifier)
        if (-not [string]::IsNullOrWhiteSpace($DisplayName)) {
            $namePatterns += $DisplayName
        }


        foreach ($namePattern in $namePatterns) {
            if ([string]::IsNullOrWhiteSpace($namePattern)) {
                continue
            }


            if ($InstalledDisplayName.Equals($namePattern, [System.StringComparison]::OrdinalIgnoreCase)) {
                return $true
            }


            if ($InstalledDisplayName.StartsWith($namePattern, [System.StringComparison]::OrdinalIgnoreCase)) {
                return $true
            }
        }


        return $false
    }


    $registryPaths = @(
        'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
        'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*',
        'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
    )


    foreach ($registryPath in $registryPaths) {
        $applications = Get-ItemProperty -Path $registryPath -ErrorAction SilentlyContinue
        foreach ($application in $applications) {
            if ([string]::IsNullOrWhiteSpace($application.DisplayName)) {
                continue
            }


            if (-not (Test-ApplicationPublisher -InstalledPublisher $application.Publisher)) {
                continue
            }


            if (Test-ApplicationDisplayName -InstalledDisplayName $application.DisplayName) {
                Write-WinGetDetectionLog -Message "Detected '$($application.DisplayName)' from uninstall registry."
                return $true
            }
        }
    }


    return $false
}


$Winget = Get-WinGetExecutablePath
$installed = if (-not [string]::IsNullOrWhiteSpace($Winget)) {
    & $Winget list --id "$PackageIdentifier" --exact --accept-source-agreements 2>&1
} else {
    @()
}
if ($installed -match $PackageIdentifierPattern) {
    Write-Output "$PackageIdentifier is installed"
    exit 0
} elseif (Test-InstalledApplicationRegistry) {
    Write-Output "$PackageIdentifier is installed"
    exit 0
} else {
    Write-Output "$PackageIdentifier is not installed"
    exit 1
}

Install script

$ErrorActionPreference = 'Stop'
$packageIdentifier = 'PuTTY.PuTTY'
$operationName = 'Install'


function Test-HydrationWinGetLogDirectory {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Path
    )


    if ([string]::IsNullOrWhiteSpace($Path)) {
        return $false
    }


    try {
        if (-not (Test-Path -Path $Path)) {
            $null = New-Item -Path $Path -ItemType Directory -Force -ErrorAction Stop
        }


        $probePath = Join-Path -Path $Path -ChildPath ("IntuneHydrationKit-LogProbe-$([guid]::NewGuid().ToString('N')).tmp")
        Set-Content -Path $probePath -Value '' -Encoding utf8 -ErrorAction Stop
        Remove-Item -Path $probePath -Force -ErrorAction SilentlyContinue
        return $true
    } catch {
        return $false
    }
}


function Get-HydrationWinGetLogDirectory {
    [CmdletBinding()]
    param()


    $programDataPath = if (-not [string]::IsNullOrWhiteSpace($env:ProgramData)) {
        $env:ProgramData
    } else {
        'C:\ProgramData'
    }


    $candidatePaths = [System.Collections.Generic.List[string]]::new()
    $candidatePaths.Add((Join-Path -Path $programDataPath -ChildPath 'Microsoft\IntuneManagementExtension\Logs'))


    if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
        $candidatePaths.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'IntuneHydrationKit\Logs'))
    }


    if (-not [string]::IsNullOrWhiteSpace($env:TEMP)) {
        $candidatePaths.Add((Join-Path -Path $env:TEMP -ChildPath 'IntuneHydrationKit\Logs'))
    }


    $systemTempPath = [System.IO.Path]::GetTempPath()
    if (-not [string]::IsNullOrWhiteSpace($systemTempPath)) {
        $candidatePaths.Add((Join-Path -Path $systemTempPath -ChildPath 'IntuneHydrationKit\Logs'))
    }


    $seenPaths = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
    foreach ($candidatePath in $candidatePaths) {
        if ([string]::IsNullOrWhiteSpace($candidatePath) -or -not $seenPaths.Add($candidatePath)) {
            continue
        }


        if (Test-HydrationWinGetLogDirectory -Path $candidatePath) {
            return $candidatePath
        }
    }


    throw 'No writable log directory was available for WinGet script execution.'
}


function Get-WinGetWrapperLogFileName {
    [CmdletBinding()]
    param()


    $safePackageIdentifier = ($packageIdentifier -replace '[^A-Za-z0-9._-]+', '-').Trim('-')
    if ([string]::IsNullOrWhiteSpace($safePackageIdentifier)) {
        $safePackageIdentifier = 'package'
    }


    return "IntuneHydrationKit-WinGet-$operationName-$safePackageIdentifier.log"
}


function Write-WinGetWrapperLog {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Message,


        [Parameter()]
        [ValidateSet('INFO', 'WARN', 'ERROR')]
        [string]$Level = 'INFO'
    )


    $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss.fff'
    Add-Content -Path $script:logPath -Value "`[$timestamp`] `[$Level`] $Message"
}


function Write-WinGetProcessStreamToLog {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Path,


        [Parameter(Mandatory)]
        [string]$Label,


        [Parameter()]
        [ValidateSet('INFO', 'WARN', 'ERROR')]
        [string]$Level = 'INFO'
    )


    if (-not (Test-Path -Path $Path)) {
        return
    }


    $lines = @(Get-Content -Path $Path -ErrorAction SilentlyContinue)
    if ($lines.Count -eq 0) {
        return
    }


    Write-WinGetWrapperLog -Message "${Label}:" -Level $Level
    foreach ($line in $lines) {
        if ([string]::IsNullOrWhiteSpace($line)) {
            continue
        }


        Write-WinGetWrapperLog -Message $line -Level $Level
    }
}


function Test-WinGetAlreadyInstalledNoUpgradeOutput {
    [CmdletBinding()]
    param(
        [Parameter()]
        [string[]]$Output
    )


    $outputText = ($Output -join [Environment]::NewLine)
    $foundExistingPackage = $outputText -match 'Found an existing package already installed\. Trying to upgrade the installed package'
    $noUpgradeAvailable = $outputText -match 'No available upgrade found' -or
        $outputText -match 'No newer package versions are available'


    return $foundExistingPackage -and $noUpgradeAvailable
}


function Get-WinGetExecutablePath {
    [CmdletBinding()]
    param()


    $programDataRoot = if ([string]::IsNullOrWhiteSpace($env:ProgramData)) { 'C:\ProgramData' } else { $env:ProgramData }
    $programDataWingetRoot = Join-Path -Path $programDataRoot -ChildPath 'Microsoft.DesktopAppInstaller'
    $programDataWingetExe = Join-Path -Path $programDataWingetRoot -ChildPath 'winget.exe'
    $isSystem = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -eq 'NT AUTHORITY\SYSTEM'


    function Test-WinGetExecutable {
        param(
            [Parameter(Mandatory)]
            [string]$Path
        )


        if (-not (Test-Path -Path $Path -PathType Leaf)) {
            return $false
        }


        try {
            $versionOutput = & $Path --version 2>&1
            return $LASTEXITCODE -eq 0 -or $versionOutput -match 'v?\d+\.\d+'
        } catch {
            return $false
        }
    }


    function Get-UserWinGetExecutablePath {
        [CmdletBinding()]
        param()


        $command = Get-Command -Name 'winget.exe' -ErrorAction SilentlyContinue
        if ($command -and -not [string]::IsNullOrWhiteSpace($command.Source) -and (Test-WinGetExecutable -Path $command.Source)) {
            return $command.Source
        }


        $searchPatterns = [System.Collections.Generic.List[string]]::new()


        if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
            $searchPatterns.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\WindowsApps\winget.exe'))
        }


        if (-not [string]::IsNullOrWhiteSpace($env:ProgramFiles)) {
            $searchPatterns.Add((Join-Path -Path $env:ProgramFiles -ChildPath 'WindowsApps\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\winget.exe'))
        }


        if (-not [string]::IsNullOrWhiteSpace(${env:ProgramFiles(x86)})) {
            $searchPatterns.Add((Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'WindowsApps\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\winget.exe'))
        }


        foreach ($pattern in $searchPatterns) {
            if ([string]::IsNullOrWhiteSpace($pattern)) {
                continue
            }


            $candidateFiles = @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | Sort-Object -Property FullName -Descending)
            if ($candidateFiles.Count -gt 0 -and (Test-WinGetExecutable -Path $candidateFiles[0].FullName)) {
                return $candidateFiles[0].FullName
            }
        }


        return $null
    }


    function Install-WinGetSystemBootstrap {
        [CmdletBinding()]
        param()


        function Get-AppInstallerMsixPath {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory)]
                [string]$Path
            )


            foreach ($filter in @('AppInstaller*_x64*.msix', 'AppInstaller*.msix')) {
                $msixPath = Get-ChildItem -Path $Path -Filter $filter -File -ErrorAction SilentlyContinue |
                    Sort-Object -Property Name -Descending |
                    Select-Object -First 1


                if ($msixPath) {
                    return $msixPath
                }
            }


            throw 'Unable to locate App Installer MSIX payload inside the downloaded bundle.'
        }


        function Invoke-WinGetBootstrapDownload {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory)]
                [string]$Uri,


                [Parameter(Mandatory)]
                [string]$OutFile
            )


            $downloadParams = @{
                Uri        = $Uri
                OutFile    = $OutFile
                TimeoutSec = 120
            }


            if ($PSVersionTable.PSVersion.Major -lt 6) {
                $downloadParams.UseBasicParsing = $true
            }


            Invoke-WebRequest @downloadParams
        }


        $tempRoot = [System.IO.Path]::GetTempPath()
        if ([string]::IsNullOrWhiteSpace($tempRoot)) {
            $tempRoot = if ([string]::IsNullOrWhiteSpace($env:TEMP)) { 'C:\Windows\Temp' } else { $env:TEMP }
        }


        $stagingRoot = Join-Path -Path $tempRoot -ChildPath 'IntuneHydrationKit-WinGetBootstrap'
        $bundlePath = Join-Path -Path $stagingRoot -ChildPath 'Microsoft.DesktopAppInstaller.msixbundle'
        $bundleExtractPath = Join-Path -Path $stagingRoot -ChildPath 'bundle'
        $msixExtractPath = Join-Path -Path $stagingRoot -ChildPath 'appinstaller'
        $vcRedistPath = Join-Path -Path $stagingRoot -ChildPath 'vc_redist.x64.exe'


        Write-WinGetWrapperLog -Message 'Resolving WinGet for current execution context.'
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        Add-Type -AssemblyName System.IO.Compression.FileSystem


        if (Test-Path -Path $stagingRoot) {
            Remove-Item -Path $stagingRoot -Recurse -Force -ErrorAction SilentlyContinue
        }


        foreach ($directoryPath in @($stagingRoot, $bundleExtractPath, $msixExtractPath)) {
            $null = New-Item -Path $directoryPath -ItemType Directory -Force
        }


        try {
            Invoke-WinGetBootstrapDownload -Uri 'https://aka.ms/vs/17/release/vc_redist.x64.exe' -OutFile $vcRedistPath
            $vcRedist = Start-Process -FilePath $vcRedistPath -ArgumentList '/q /norestart' -Wait -PassThru
            Write-WinGetWrapperLog -Message "VC++ bootstrap exited with code $($vcRedist.ExitCode)."
        } catch {
            Write-WinGetWrapperLog -Message "VC++ bootstrap failed: $($_.Exception.Message)" -Level 'WARN'
        }


        Invoke-WinGetBootstrapDownload -Uri 'https://aka.ms/getwinget' -OutFile $bundlePath
        [System.IO.Compression.ZipFile]::ExtractToDirectory($bundlePath, $bundleExtractPath)
        $msixPath = Get-AppInstallerMsixPath -Path $bundleExtractPath


        if (Test-Path -Path $programDataWingetRoot) {
            Remove-Item -Path $programDataWingetRoot -Recurse -Force -ErrorAction SilentlyContinue
        }


        $null = New-Item -Path $programDataWingetRoot -ItemType Directory -Force
        [System.IO.Compression.ZipFile]::ExtractToDirectory($msixPath.FullName, $msixExtractPath)
        Copy-Item -Path (Join-Path -Path $msixExtractPath -ChildPath '*') -Destination $programDataWingetRoot -Recurse -Force
        Write-WinGetWrapperLog -Message "Bootstrapped WinGet to '$programDataWingetRoot'."
    }


    if (-not $isSystem) {
        $userWingetExe = Get-UserWinGetExecutablePath
        if (-not [string]::IsNullOrWhiteSpace($userWingetExe)) {
            return $userWingetExe
        }


        if (Test-WinGetExecutable -Path $programDataWingetExe) {
            return $programDataWingetExe
        }


        throw 'winget.exe could not be located for this user context. Ensure App Installer is installed for the signed-in user or pre-bootstrap WinGet in SYSTEM context.'
    }


    if (Test-WinGetExecutable -Path $programDataWingetExe) {
        return $programDataWingetExe
    }


    Install-WinGetSystemBootstrap
    if (Test-WinGetExecutable -Path $programDataWingetExe) {
        return $programDataWingetExe
    }


    throw 'winget.exe could not be located or bootstrapped successfully for this context.'
}


$wingetCommand = 'winget install --id PuTTY.PuTTY --exact --silent --scope machine --accept-package-agreements --accept-source-agreements'
$argumentString = ($wingetCommand -replace '^\s*winget(?:\.exe)?\s*', '').Trim()
if ([string]::IsNullOrWhiteSpace($argumentString)) {
    throw "Unable to derive WinGet arguments from command '$wingetCommand'."
}


$logDirectory = Get-HydrationWinGetLogDirectory
$logFileName = Get-WinGetWrapperLogFileName
$script:logPath = Join-Path -Path $logDirectory -ChildPath $logFileName
$baseLogName = [System.IO.Path]::GetFileNameWithoutExtension($logFileName)
$stdoutPath = Join-Path -Path $logDirectory -ChildPath "$baseLogName.stdout.log"
$stderrPath = Join-Path -Path $logDirectory -ChildPath "$baseLogName.stderr.log"


foreach ($streamPath in @($stdoutPath, $stderrPath)) {
    if (Test-Path -Path $streamPath) {
        Remove-Item -Path $streamPath -Force -ErrorAction SilentlyContinue
    }
}


Write-WinGetWrapperLog -Message "Starting $operationName for package '$packageIdentifier'."
Write-WinGetWrapperLog -Message "Resolved IME log path: $script:logPath"
Write-WinGetWrapperLog -Message "Executing WinGet command: $wingetCommand"


try {
    $wingetPath = Get-WinGetExecutablePath
    Write-WinGetWrapperLog -Message "Resolved winget executable: $wingetPath"
    $process = Start-Process -FilePath $wingetPath -ArgumentList $argumentString -Wait -PassThru -NoNewWindow -RedirectStandardOutput $stdoutPath -RedirectStandardError $stderrPath
    Write-WinGetProcessStreamToLog -Path $stdoutPath -Label 'WinGet standard output'
    Write-WinGetProcessStreamToLog -Path $stderrPath -Label 'WinGet standard error' -Level 'WARN'
    $standardOutput = if (Test-Path -Path $stdoutPath) { @(Get-Content -Path $stdoutPath -ErrorAction SilentlyContinue) } else { @() }
    $exitCode = [int]$process.ExitCode
    Write-WinGetWrapperLog -Message "WinGet process exited with code $exitCode."
    if ($operationName -eq 'Install' -and ($exitCode -eq -1978335189 -or (Test-WinGetAlreadyInstalledNoUpgradeOutput -Output $standardOutput))) {
        Write-WinGetWrapperLog -Message "Package already installed (no upgrade needed). Treating as success." -Level 'INFO'
        $exitCode = 0
    }
    exit $exitCode
} catch {
    Write-WinGetProcessStreamToLog -Path $stdoutPath -Label 'WinGet standard output'
    Write-WinGetProcessStreamToLog -Path $stderrPath -Label 'WinGet standard error' -Level 'WARN'
    Write-WinGetWrapperLog -Message "Wrapper execution failed: $($_.Exception.Message)" -Level 'ERROR'
    throw
}

Uninstall script

$ErrorActionPreference = 'Stop'
$packageIdentifier = 'PuTTY.PuTTY'
$operationName = 'Uninstall'


function Test-HydrationWinGetLogDirectory {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Path
    )


    if ([string]::IsNullOrWhiteSpace($Path)) {
        return $false
    }


    try {
        if (-not (Test-Path -Path $Path)) {
            $null = New-Item -Path $Path -ItemType Directory -Force -ErrorAction Stop
        }


        $probePath = Join-Path -Path $Path -ChildPath ("IntuneHydrationKit-LogProbe-$([guid]::NewGuid().ToString('N')).tmp")
        Set-Content -Path $probePath -Value '' -Encoding utf8 -ErrorAction Stop
        Remove-Item -Path $probePath -Force -ErrorAction SilentlyContinue
        return $true
    } catch {
        return $false
    }
}


function Get-HydrationWinGetLogDirectory {
    [CmdletBinding()]
    param()


    $programDataPath = if (-not [string]::IsNullOrWhiteSpace($env:ProgramData)) {
        $env:ProgramData
    } else {
        'C:\ProgramData'
    }


    $candidatePaths = [System.Collections.Generic.List[string]]::new()
    $candidatePaths.Add((Join-Path -Path $programDataPath -ChildPath 'Microsoft\IntuneManagementExtension\Logs'))


    if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
        $candidatePaths.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'IntuneHydrationKit\Logs'))
    }


    if (-not [string]::IsNullOrWhiteSpace($env:TEMP)) {
        $candidatePaths.Add((Join-Path -Path $env:TEMP -ChildPath 'IntuneHydrationKit\Logs'))
    }


    $systemTempPath = [System.IO.Path]::GetTempPath()
    if (-not [string]::IsNullOrWhiteSpace($systemTempPath)) {
        $candidatePaths.Add((Join-Path -Path $systemTempPath -ChildPath 'IntuneHydrationKit\Logs'))
    }


    $seenPaths = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
    foreach ($candidatePath in $candidatePaths) {
        if ([string]::IsNullOrWhiteSpace($candidatePath) -or -not $seenPaths.Add($candidatePath)) {
            continue
        }


        if (Test-HydrationWinGetLogDirectory -Path $candidatePath) {
            return $candidatePath
        }
    }


    throw 'No writable log directory was available for WinGet script execution.'
}


function Get-WinGetWrapperLogFileName {
    [CmdletBinding()]
    param()


    $safePackageIdentifier = ($packageIdentifier -replace '[^A-Za-z0-9._-]+', '-').Trim('-')
    if ([string]::IsNullOrWhiteSpace($safePackageIdentifier)) {
        $safePackageIdentifier = 'package'
    }


    return "IntuneHydrationKit-WinGet-$operationName-$safePackageIdentifier.log"
}


function Write-WinGetWrapperLog {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Message,


        [Parameter()]
        [ValidateSet('INFO', 'WARN', 'ERROR')]
        [string]$Level = 'INFO'
    )


    $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss.fff'
    Add-Content -Path $script:logPath -Value "`[$timestamp`] `[$Level`] $Message"
}


function Write-WinGetProcessStreamToLog {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Path,


        [Parameter(Mandatory)]
        [string]$Label,


        [Parameter()]
        [ValidateSet('INFO', 'WARN', 'ERROR')]
        [string]$Level = 'INFO'
    )


    if (-not (Test-Path -Path $Path)) {
        return
    }


    $lines = @(Get-Content -Path $Path -ErrorAction SilentlyContinue)
    if ($lines.Count -eq 0) {
        return
    }


    Write-WinGetWrapperLog -Message "${Label}:" -Level $Level
    foreach ($line in $lines) {
        if ([string]::IsNullOrWhiteSpace($line)) {
            continue
        }


        Write-WinGetWrapperLog -Message $line -Level $Level
    }
}


function Test-WinGetAlreadyInstalledNoUpgradeOutput {
    [CmdletBinding()]
    param(
        [Parameter()]
        [string[]]$Output
    )


    $outputText = ($Output -join [Environment]::NewLine)
    $foundExistingPackage = $outputText -match 'Found an existing package already installed\. Trying to upgrade the installed package'
    $noUpgradeAvailable = $outputText -match 'No available upgrade found' -or
        $outputText -match 'No newer package versions are available'


    return $foundExistingPackage -and $noUpgradeAvailable
}


function Get-WinGetExecutablePath {
    [CmdletBinding()]
    param()


    $programDataRoot = if ([string]::IsNullOrWhiteSpace($env:ProgramData)) { 'C:\ProgramData' } else { $env:ProgramData }
    $programDataWingetRoot = Join-Path -Path $programDataRoot -ChildPath 'Microsoft.DesktopAppInstaller'
    $programDataWingetExe = Join-Path -Path $programDataWingetRoot -ChildPath 'winget.exe'
    $isSystem = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -eq 'NT AUTHORITY\SYSTEM'


    function Test-WinGetExecutable {
        param(
            [Parameter(Mandatory)]
            [string]$Path
        )


        if (-not (Test-Path -Path $Path -PathType Leaf)) {
            return $false
        }


        try {
            $versionOutput = & $Path --version 2>&1
            return $LASTEXITCODE -eq 0 -or $versionOutput -match 'v?\d+\.\d+'
        } catch {
            return $false
        }
    }


    function Get-UserWinGetExecutablePath {
        [CmdletBinding()]
        param()


        $command = Get-Command -Name 'winget.exe' -ErrorAction SilentlyContinue
        if ($command -and -not [string]::IsNullOrWhiteSpace($command.Source) -and (Test-WinGetExecutable -Path $command.Source)) {
            return $command.Source
        }


        $searchPatterns = [System.Collections.Generic.List[string]]::new()


        if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
            $searchPatterns.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\WindowsApps\winget.exe'))
        }


        if (-not [string]::IsNullOrWhiteSpace($env:ProgramFiles)) {
            $searchPatterns.Add((Join-Path -Path $env:ProgramFiles -ChildPath 'WindowsApps\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\winget.exe'))
        }


        if (-not [string]::IsNullOrWhiteSpace(${env:ProgramFiles(x86)})) {
            $searchPatterns.Add((Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'WindowsApps\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\winget.exe'))
        }


        foreach ($pattern in $searchPatterns) {
            if ([string]::IsNullOrWhiteSpace($pattern)) {
                continue
            }


            $candidateFiles = @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | Sort-Object -Property FullName -Descending)
            if ($candidateFiles.Count -gt 0 -and (Test-WinGetExecutable -Path $candidateFiles[0].FullName)) {
                return $candidateFiles[0].FullName
            }
        }


        return $null
    }


    function Install-WinGetSystemBootstrap {
        [CmdletBinding()]
        param()


        function Get-AppInstallerMsixPath {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory)]
                [string]$Path
            )


            foreach ($filter in @('AppInstaller*_x64*.msix', 'AppInstaller*.msix')) {
                $msixPath = Get-ChildItem -Path $Path -Filter $filter -File -ErrorAction SilentlyContinue |
                    Sort-Object -Property Name -Descending |
                    Select-Object -First 1


                if ($msixPath) {
                    return $msixPath
                }
            }


            throw 'Unable to locate App Installer MSIX payload inside the downloaded bundle.'
        }


        function Invoke-WinGetBootstrapDownload {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory)]
                [string]$Uri,


                [Parameter(Mandatory)]
                [string]$OutFile
            )


            $downloadParams = @{
                Uri        = $Uri
                OutFile    = $OutFile
                TimeoutSec = 120
            }


            if ($PSVersionTable.PSVersion.Major -lt 6) {
                $downloadParams.UseBasicParsing = $true
            }


            Invoke-WebRequest @downloadParams
        }


        $tempRoot = [System.IO.Path]::GetTempPath()
        if ([string]::IsNullOrWhiteSpace($tempRoot)) {
            $tempRoot = if ([string]::IsNullOrWhiteSpace($env:TEMP)) { 'C:\Windows\Temp' } else { $env:TEMP }
        }


        $stagingRoot = Join-Path -Path $tempRoot -ChildPath 'IntuneHydrationKit-WinGetBootstrap'
        $bundlePath = Join-Path -Path $stagingRoot -ChildPath 'Microsoft.DesktopAppInstaller.msixbundle'
        $bundleExtractPath = Join-Path -Path $stagingRoot -ChildPath 'bundle'
        $msixExtractPath = Join-Path -Path $stagingRoot -ChildPath 'appinstaller'
        $vcRedistPath = Join-Path -Path $stagingRoot -ChildPath 'vc_redist.x64.exe'


        Write-WinGetWrapperLog -Message 'Resolving WinGet for current execution context.'
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        Add-Type -AssemblyName System.IO.Compression.FileSystem


        if (Test-Path -Path $stagingRoot) {
            Remove-Item -Path $stagingRoot -Recurse -Force -ErrorAction SilentlyContinue
        }


        foreach ($directoryPath in @($stagingRoot, $bundleExtractPath, $msixExtractPath)) {
            $null = New-Item -Path $directoryPath -ItemType Directory -Force
        }


        try {
            Invoke-WinGetBootstrapDownload -Uri 'https://aka.ms/vs/17/release/vc_redist.x64.exe' -OutFile $vcRedistPath
            $vcRedist = Start-Process -FilePath $vcRedistPath -ArgumentList '/q /norestart' -Wait -PassThru
            Write-WinGetWrapperLog -Message "VC++ bootstrap exited with code $($vcRedist.ExitCode)."
        } catch {
            Write-WinGetWrapperLog -Message "VC++ bootstrap failed: $($_.Exception.Message)" -Level 'WARN'
        }


        Invoke-WinGetBootstrapDownload -Uri 'https://aka.ms/getwinget' -OutFile $bundlePath
        [System.IO.Compression.ZipFile]::ExtractToDirectory($bundlePath, $bundleExtractPath)
        $msixPath = Get-AppInstallerMsixPath -Path $bundleExtractPath


        if (Test-Path -Path $programDataWingetRoot) {
            Remove-Item -Path $programDataWingetRoot -Recurse -Force -ErrorAction SilentlyContinue
        }


        $null = New-Item -Path $programDataWingetRoot -ItemType Directory -Force
        [System.IO.Compression.ZipFile]::ExtractToDirectory($msixPath.FullName, $msixExtractPath)
        Copy-Item -Path (Join-Path -Path $msixExtractPath -ChildPath '*') -Destination $programDataWingetRoot -Recurse -Force
        Write-WinGetWrapperLog -Message "Bootstrapped WinGet to '$programDataWingetRoot'."
    }


    if (-not $isSystem) {
        $userWingetExe = Get-UserWinGetExecutablePath
        if (-not [string]::IsNullOrWhiteSpace($userWingetExe)) {
            return $userWingetExe
        }


        if (Test-WinGetExecutable -Path $programDataWingetExe) {
            return $programDataWingetExe
        }


        throw 'winget.exe could not be located for this user context. Ensure App Installer is installed for the signed-in user or pre-bootstrap WinGet in SYSTEM context.'
    }


    if (Test-WinGetExecutable -Path $programDataWingetExe) {
        return $programDataWingetExe
    }


    Install-WinGetSystemBootstrap
    if (Test-WinGetExecutable -Path $programDataWingetExe) {
        return $programDataWingetExe
    }


    throw 'winget.exe could not be located or bootstrapped successfully for this context.'
}


$wingetCommand = 'winget uninstall --id PuTTY.PuTTY --exact --scope machine --silent'
$argumentString = ($wingetCommand -replace '^\s*winget(?:\.exe)?\s*', '').Trim()
if ([string]::IsNullOrWhiteSpace($argumentString)) {
    throw "Unable to derive WinGet arguments from command '$wingetCommand'."
}


$logDirectory = Get-HydrationWinGetLogDirectory
$logFileName = Get-WinGetWrapperLogFileName
$script:logPath = Join-Path -Path $logDirectory -ChildPath $logFileName
$baseLogName = [System.IO.Path]::GetFileNameWithoutExtension($logFileName)
$stdoutPath = Join-Path -Path $logDirectory -ChildPath "$baseLogName.stdout.log"
$stderrPath = Join-Path -Path $logDirectory -ChildPath "$baseLogName.stderr.log"


foreach ($streamPath in @($stdoutPath, $stderrPath)) {
    if (Test-Path -Path $streamPath) {
        Remove-Item -Path $streamPath -Force -ErrorAction SilentlyContinue
    }
}


Write-WinGetWrapperLog -Message "Starting $operationName for package '$packageIdentifier'."
Write-WinGetWrapperLog -Message "Resolved IME log path: $script:logPath"
Write-WinGetWrapperLog -Message "Executing WinGet command: $wingetCommand"


try {
    $wingetPath = Get-WinGetExecutablePath
    Write-WinGetWrapperLog -Message "Resolved winget executable: $wingetPath"
    $process = Start-Process -FilePath $wingetPath -ArgumentList $argumentString -Wait -PassThru -NoNewWindow -RedirectStandardOutput $stdoutPath -RedirectStandardError $stderrPath
    Write-WinGetProcessStreamToLog -Path $stdoutPath -Label 'WinGet standard output'
    Write-WinGetProcessStreamToLog -Path $stderrPath -Label 'WinGet standard error' -Level 'WARN'
    $standardOutput = if (Test-Path -Path $stdoutPath) { @(Get-Content -Path $stdoutPath -ErrorAction SilentlyContinue) } else { @() }
    $exitCode = [int]$process.ExitCode
    Write-WinGetWrapperLog -Message "WinGet process exited with code $exitCode."
    if ($operationName -eq 'Install' -and ($exitCode -eq -1978335189 -or (Test-WinGetAlreadyInstalledNoUpgradeOutput -Output $standardOutput))) {
        Write-WinGetWrapperLog -Message "Package already installed (no upgrade needed). Treating as success." -Level 'INFO'
        $exitCode = 0
    }
    exit $exitCode
} catch {
    Write-WinGetProcessStreamToLog -Path $stdoutPath -Label 'WinGet standard output'
    Write-WinGetProcessStreamToLog -Path $stderrPath -Label 'WinGet standard error' -Level 'WARN'
    Write-WinGetWrapperLog -Message "Wrapper execution failed: $($_.Exception.Message)" -Level 'ERROR'
    throw
}

Import-ready JSON

Payload
{
  "id": "putty",
  "packageIdentifier": "PuTTY.PuTTY",
  "displayName": "PuTTY - [IHD]",
  "packageFileName": "putty.intunewin",
  "publisher": "Simon Tatham",
  "developer": "Simon Tatham",
  "owner": "",
  "version": "latest",
  "description": "Starter-pack WinGet template for PuTTY Win32 packaging.",
  "notes": "Imported from WinGet\nWinGetPackageIdentifier: PuTTY.PuTTY\nWinGetPackageVersion: latest\nWinGetTemplateId: putty\nWinGetManifestRepository: microsoft/winget-pkgs\nWinGetManifestPath: manifests/p/PuTTY/PuTTY",
  "setupFilePath": "Install-WinGetPackage.ps1",
  "installCommandLine": "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File .\\Install-WinGetPackage.ps1",
  "uninstallCommandLine": "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File .\\Uninstall-WinGetPackage.ps1",
  "minimumSupportedOperatingSystem": {
    "v10_21H1": true
  },
  "applicableArchitectures": "x64",
  "allowAvailableUninstall": true,
  "winget": {
    "packageIdentifier": "PuTTY.PuTTY",
    "displayName": "PuTTY",
    "publisher": "Simon Tatham",
    "manifestPath": "manifests/p/PuTTY/PuTTY"
  },
  "catalogSubcategory": "WinGet catalog app",
  "optIn": true,
  "detectionScriptContent": "$PackageIdentifier = 'PuTTY.PuTTY'\n$PackageIdentifierPattern = 'PuTTY\\.PuTTY'\n$DisplayName = 'PuTTY'\n$Publisher = 'Simon Tatham'\n\nfunction Write-WinGetDetectionLog {\n    [CmdletBinding()]\n    param(\n        [Parameter(Mandatory)]\n        [string]$Message,\n\n        [Parameter()]\n        [ValidateSet('INFO', 'WARN', 'ERROR')]\n        [string]$Level = 'INFO'\n    )\n\n    Write-Verbose \"[$Level] $Message\"\n}\n\nfunction Get-WinGetExecutablePath {\n    [CmdletBinding()]\n    param()\n\n    $programDataRoot = if ([string]::IsNullOrWhiteSpace($env:ProgramData)) { 'C:\\ProgramData' } else { $env:ProgramData }\n    $programDataWingetRoot = Join-Path -Path $programDataRoot -ChildPath 'Microsoft.DesktopAppInstaller'\n    $programDataWingetExe = Join-Path -Path $programDataWingetRoot -ChildPath 'winget.exe'\n    $isSystem = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -eq 'NT AUTHORITY\\SYSTEM'\n\n    function Test-WinGetExecutable {\n        param(\n            [Parameter(Mandatory)]\n            [string]$Path\n        )\n\n        if (-not (Test-Path -Path $Path -PathType Leaf)) {\n            return $false\n        }\n\n        try {\n            $versionOutput = & $Path --version 2>&1\n            return $LASTEXITCODE -eq 0 -or $versionOutput -match 'v?\\d+\\.\\d+'\n        } catch {\n            return $false\n        }\n    }\n\n    function Get-UserWinGetExecutablePath {\n        [CmdletBinding()]\n        param()\n\n        $command = Get-Command -Name 'winget.exe' -ErrorAction SilentlyContinue\n        if ($command -and -not [string]::IsNullOrWhiteSpace($command.Source) -and (Test-WinGetExecutable -Path $command.Source)) {\n            return $command.Source\n        }\n\n        $searchPatterns = [System.Collections.Generic.List[string]]::new()\n\n        if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {\n            $searchPatterns.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\\WindowsApps\\winget.exe'))\n        }\n\n        if (-not [string]::IsNullOrWhiteSpace($env:ProgramFiles)) {\n            $searchPatterns.Add((Join-Path -Path $env:ProgramFiles -ChildPath 'WindowsApps\\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\\winget.exe'))\n        }\n\n        if (-not [string]::IsNullOrWhiteSpace(${env:ProgramFiles(x86)})) {\n            $searchPatterns.Add((Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'WindowsApps\\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\\winget.exe'))\n        }\n\n        foreach ($pattern in $searchPatterns) {\n            if ([string]::IsNullOrWhiteSpace($pattern)) {\n                continue\n            }\n\n            $candidateFiles = @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | Sort-Object -Property FullName -Descending)\n            if ($candidateFiles.Count -gt 0 -and (Test-WinGetExecutable -Path $candidateFiles[0].FullName)) {\n                return $candidateFiles[0].FullName\n            }\n        }\n\n        return $null\n    }\n\n    if (-not $isSystem) {\n        $userWingetExe = Get-UserWinGetExecutablePath\n        if (-not [string]::IsNullOrWhiteSpace($userWingetExe)) {\n            return $userWingetExe\n        }\n\n        if (Test-WinGetExecutable -Path $programDataWingetExe) {\n            return $programDataWingetExe\n        }\n\n        return $null\n    }\n\n    if (Test-WinGetExecutable -Path $programDataWingetExe) {\n        return $programDataWingetExe\n    }\n\n    return $null\n}\n\nfunction Test-InstalledApplicationRegistry {\n    [CmdletBinding()]\n    param()\n\n    function Test-ApplicationPublisher {\n        [CmdletBinding()]\n        param(\n            [Parameter()]\n            [string]$InstalledPublisher\n        )\n\n        if ([string]::IsNullOrWhiteSpace($Publisher)) {\n            return $true\n        }\n\n        if ([string]::IsNullOrWhiteSpace($InstalledPublisher)) {\n            return $false\n        }\n\n        return $InstalledPublisher.IndexOf($Publisher, [System.StringComparison]::OrdinalIgnoreCase) -ge 0\n    }\n\n    function Test-ApplicationDisplayName {\n        [CmdletBinding()]\n        param(\n            [Parameter(Mandatory)]\n            [string]$InstalledDisplayName\n        )\n\n        $namePatterns = @($PackageIdentifier)\n        if (-not [string]::IsNullOrWhiteSpace($DisplayName)) {\n            $namePatterns += $DisplayName\n        }\n\n        foreach ($namePattern in $namePatterns) {\n            if ([string]::IsNullOrWhiteSpace($namePattern)) {\n                continue\n            }\n\n            if ($InstalledDisplayName.Equals($namePattern, [System.StringComparison]::OrdinalIgnoreCase)) {\n                return $true\n            }\n\n            if ($InstalledDisplayName.StartsWith($namePattern, [System.StringComparison]::OrdinalIgnoreCase)) {\n                return $true\n            }\n        }\n\n        return $false\n    }\n\n    $registryPaths = @(\n        'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*',\n        'HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*',\n        'HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'\n    )\n\n    foreach ($registryPath in $registryPaths) {\n        $applications = Get-ItemProperty -Path $registryPath -ErrorAction SilentlyContinue\n        foreach ($application in $applications) {\n            if ([string]::IsNullOrWhiteSpace($application.DisplayName)) {\n                continue\n            }\n\n            if (-not (Test-ApplicationPublisher -InstalledPublisher $application.Publisher)) {\n                continue\n            }\n\n            if (Test-ApplicationDisplayName -InstalledDisplayName $application.DisplayName) {\n                Write-WinGetDetectionLog -Message \"Detected '$($application.DisplayName)' from uninstall registry.\"\n                return $true\n            }\n        }\n    }\n\n    return $false\n}\n\n$Winget = Get-WinGetExecutablePath\n$installed = if (-not [string]::IsNullOrWhiteSpace($Winget)) {\n    & $Winget list --id \"$PackageIdentifier\" --exact --accept-source-agreements 2>&1\n} else {\n    @()\n}\nif ($installed -match $PackageIdentifierPattern) {\n    Write-Output \"$PackageIdentifier is installed\"\n    exit 0\n} elseif (Test-InstalledApplicationRegistry) {\n    Write-Output \"$PackageIdentifier is installed\"\n    exit 0\n} else {\n    Write-Output \"$PackageIdentifier is not installed\"\n    exit 1\n}\n",
  "installScriptContent": "$ErrorActionPreference = 'Stop'\n$packageIdentifier = 'PuTTY.PuTTY'\n$operationName = 'Install'\n\nfunction Test-HydrationWinGetLogDirectory {\n    [CmdletBinding()]\n    param(\n        [Parameter(Mandatory)]\n        [string]$Path\n    )\n\n    if ([string]::IsNullOrWhiteSpace($Path)) {\n        return $false\n    }\n\n    try {\n        if (-not (Test-Path -Path $Path)) {\n            $null = New-Item -Path $Path -ItemType Directory -Force -ErrorAction Stop\n        }\n\n        $probePath = Join-Path -Path $Path -ChildPath (\"IntuneHydrationKit-LogProbe-$([guid]::NewGuid().ToString('N')).tmp\")\n        Set-Content -Path $probePath -Value '' -Encoding utf8 -ErrorAction Stop\n        Remove-Item -Path $probePath -Force -ErrorAction SilentlyContinue\n        return $true\n    } catch {\n        return $false\n    }\n}\n\nfunction Get-HydrationWinGetLogDirectory {\n    [CmdletBinding()]\n    param()\n\n    $programDataPath = if (-not [string]::IsNullOrWhiteSpace($env:ProgramData)) {\n        $env:ProgramData\n    } else {\n        'C:\\ProgramData'\n    }\n\n    $candidatePaths = [System.Collections.Generic.List[string]]::new()\n    $candidatePaths.Add((Join-Path -Path $programDataPath -ChildPath 'Microsoft\\IntuneManagementExtension\\Logs'))\n\n    if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {\n        $candidatePaths.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'IntuneHydrationKit\\Logs'))\n    }\n\n    if (-not [string]::IsNullOrWhiteSpace($env:TEMP)) {\n        $candidatePaths.Add((Join-Path -Path $env:TEMP -ChildPath 'IntuneHydrationKit\\Logs'))\n    }\n\n    $systemTempPath = [System.IO.Path]::GetTempPath()\n    if (-not [string]::IsNullOrWhiteSpace($systemTempPath)) {\n        $candidatePaths.Add((Join-Path -Path $systemTempPath -ChildPath 'IntuneHydrationKit\\Logs'))\n    }\n\n    $seenPaths = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)\n    foreach ($candidatePath in $candidatePaths) {\n        if ([string]::IsNullOrWhiteSpace($candidatePath) -or -not $seenPaths.Add($candidatePath)) {\n            continue\n        }\n\n        if (Test-HydrationWinGetLogDirectory -Path $candidatePath) {\n            return $candidatePath\n        }\n    }\n\n    throw 'No writable log directory was available for WinGet script execution.'\n}\n\nfunction Get-WinGetWrapperLogFileName {\n    [CmdletBinding()]\n    param()\n\n    $safePackageIdentifier = ($packageIdentifier -replace '[^A-Za-z0-9._-]+', '-').Trim('-')\n    if ([string]::IsNullOrWhiteSpace($safePackageIdentifier)) {\n        $safePackageIdentifier = 'package'\n    }\n\n    return \"IntuneHydrationKit-WinGet-$operationName-$safePackageIdentifier.log\"\n}\n\nfunction Write-WinGetWrapperLog {\n    [CmdletBinding()]\n    param(\n        [Parameter(Mandatory)]\n        [string]$Message,\n\n        [Parameter()]\n        [ValidateSet('INFO', 'WARN', 'ERROR')]\n        [string]$Level = 'INFO'\n    )\n\n    $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss.fff'\n    Add-Content -Path $script:logPath -Value \"`[$timestamp`] `[$Level`] $Message\"\n}\n\nfunction Write-WinGetProcessStreamToLog {\n    [CmdletBinding()]\n    param(\n        [Parameter(Mandatory)]\n        [string]$Path,\n\n        [Parameter(Mandatory)]\n        [string]$Label,\n\n        [Parameter()]\n        [ValidateSet('INFO', 'WARN', 'ERROR')]\n        [string]$Level = 'INFO'\n    )\n\n    if (-not (Test-Path -Path $Path)) {\n        return\n    }\n\n    $lines = @(Get-Content -Path $Path -ErrorAction SilentlyContinue)\n    if ($lines.Count -eq 0) {\n        return\n    }\n\n    Write-WinGetWrapperLog -Message \"${Label}:\" -Level $Level\n    foreach ($line in $lines) {\n        if ([string]::IsNullOrWhiteSpace($line)) {\n            continue\n        }\n\n        Write-WinGetWrapperLog -Message $line -Level $Level\n    }\n}\n\nfunction Test-WinGetAlreadyInstalledNoUpgradeOutput {\n    [CmdletBinding()]\n    param(\n        [Parameter()]\n        [string[]]$Output\n    )\n\n    $outputText = ($Output -join [Environment]::NewLine)\n    $foundExistingPackage = $outputText -match 'Found an existing package already installed\\. Trying to upgrade the installed package'\n    $noUpgradeAvailable = $outputText -match 'No available upgrade found' -or\n        $outputText -match 'No newer package versions are available'\n\n    return $foundExistingPackage -and $noUpgradeAvailable\n}\n\nfunction Get-WinGetExecutablePath {\n    [CmdletBinding()]\n    param()\n\n    $programDataRoot = if ([string]::IsNullOrWhiteSpace($env:ProgramData)) { 'C:\\ProgramData' } else { $env:ProgramData }\n    $programDataWingetRoot = Join-Path -Path $programDataRoot -ChildPath 'Microsoft.DesktopAppInstaller'\n    $programDataWingetExe = Join-Path -Path $programDataWingetRoot -ChildPath 'winget.exe'\n    $isSystem = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -eq 'NT AUTHORITY\\SYSTEM'\n\n    function Test-WinGetExecutable {\n        param(\n            [Parameter(Mandatory)]\n            [string]$Path\n        )\n\n        if (-not (Test-Path -Path $Path -PathType Leaf)) {\n            return $false\n        }\n\n        try {\n            $versionOutput = & $Path --version 2>&1\n            return $LASTEXITCODE -eq 0 -or $versionOutput -match 'v?\\d+\\.\\d+'\n        } catch {\n            return $false\n        }\n    }\n\n    function Get-UserWinGetExecutablePath {\n        [CmdletBinding()]\n        param()\n\n        $command = Get-Command -Name 'winget.exe' -ErrorAction SilentlyContinue\n        if ($command -and -not [string]::IsNullOrWhiteSpace($command.Source) -and (Test-WinGetExecutable -Path $command.Source)) {\n            return $command.Source\n        }\n\n        $searchPatterns = [System.Collections.Generic.List[string]]::new()\n\n        if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {\n            $searchPatterns.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\\WindowsApps\\winget.exe'))\n        }\n\n        if (-not [string]::IsNullOrWhiteSpace($env:ProgramFiles)) {\n            $searchPatterns.Add((Join-Path -Path $env:ProgramFiles -ChildPath 'WindowsApps\\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\\winget.exe'))\n        }\n\n        if (-not [string]::IsNullOrWhiteSpace(${env:ProgramFiles(x86)})) {\n            $searchPatterns.Add((Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'WindowsApps\\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\\winget.exe'))\n        }\n\n        foreach ($pattern in $searchPatterns) {\n            if ([string]::IsNullOrWhiteSpace($pattern)) {\n                continue\n            }\n\n            $candidateFiles = @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | Sort-Object -Property FullName -Descending)\n            if ($candidateFiles.Count -gt 0 -and (Test-WinGetExecutable -Path $candidateFiles[0].FullName)) {\n                return $candidateFiles[0].FullName\n            }\n        }\n\n        return $null\n    }\n\n    function Install-WinGetSystemBootstrap {\n        [CmdletBinding()]\n        param()\n\n        function Get-AppInstallerMsixPath {\n            [CmdletBinding()]\n            param(\n                [Parameter(Mandatory)]\n                [string]$Path\n            )\n\n            foreach ($filter in @('AppInstaller*_x64*.msix', 'AppInstaller*.msix')) {\n                $msixPath = Get-ChildItem -Path $Path -Filter $filter -File -ErrorAction SilentlyContinue |\n                    Sort-Object -Property Name -Descending |\n                    Select-Object -First 1\n\n                if ($msixPath) {\n                    return $msixPath\n                }\n            }\n\n            throw 'Unable to locate App Installer MSIX payload inside the downloaded bundle.'\n        }\n\n        function Invoke-WinGetBootstrapDownload {\n            [CmdletBinding()]\n            param(\n                [Parameter(Mandatory)]\n                [string]$Uri,\n\n                [Parameter(Mandatory)]\n                [string]$OutFile\n            )\n\n            $downloadParams = @{\n                Uri        = $Uri\n                OutFile    = $OutFile\n                TimeoutSec = 120\n            }\n\n            if ($PSVersionTable.PSVersion.Major -lt 6) {\n                $downloadParams.UseBasicParsing = $true\n            }\n\n            Invoke-WebRequest @downloadParams\n        }\n\n        $tempRoot = [System.IO.Path]::GetTempPath()\n        if ([string]::IsNullOrWhiteSpace($tempRoot)) {\n            $tempRoot = if ([string]::IsNullOrWhiteSpace($env:TEMP)) { 'C:\\Windows\\Temp' } else { $env:TEMP }\n        }\n\n        $stagingRoot = Join-Path -Path $tempRoot -ChildPath 'IntuneHydrationKit-WinGetBootstrap'\n        $bundlePath = Join-Path -Path $stagingRoot -ChildPath 'Microsoft.DesktopAppInstaller.msixbundle'\n        $bundleExtractPath = Join-Path -Path $stagingRoot -ChildPath 'bundle'\n        $msixExtractPath = Join-Path -Path $stagingRoot -ChildPath 'appinstaller'\n        $vcRedistPath = Join-Path -Path $stagingRoot -ChildPath 'vc_redist.x64.exe'\n\n        Write-WinGetWrapperLog -Message 'Resolving WinGet for current execution context.'\n        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12\n        Add-Type -AssemblyName System.IO.Compression.FileSystem\n\n        if (Test-Path -Path $stagingRoot) {\n            Remove-Item -Path $stagingRoot -Recurse -Force -ErrorAction SilentlyContinue\n        }\n\n        foreach ($directoryPath in @($stagingRoot, $bundleExtractPath, $msixExtractPath)) {\n            $null = New-Item -Path $directoryPath -ItemType Directory -Force\n        }\n\n        try {\n            Invoke-WinGetBootstrapDownload -Uri 'https://aka.ms/vs/17/release/vc_redist.x64.exe' -OutFile $vcRedistPath\n            $vcRedist = Start-Process -FilePath $vcRedistPath -ArgumentList '/q /norestart' -Wait -PassThru\n            Write-WinGetWrapperLog -Message \"VC++ bootstrap exited with code $($vcRedist.ExitCode).\"\n        } catch {\n            Write-WinGetWrapperLog -Message \"VC++ bootstrap failed: $($_.Exception.Message)\" -Level 'WARN'\n        }\n\n        Invoke-WinGetBootstrapDownload -Uri 'https://aka.ms/getwinget' -OutFile $bundlePath\n        [System.IO.Compression.ZipFile]::ExtractToDirectory($bundlePath, $bundleExtractPath)\n        $msixPath = Get-AppInstallerMsixPath -Path $bundleExtractPath\n\n        if (Test-Path -Path $programDataWingetRoot) {\n            Remove-Item -Path $programDataWingetRoot -Recurse -Force -ErrorAction SilentlyContinue\n        }\n\n        $null = New-Item -Path $programDataWingetRoot -ItemType Directory -Force\n        [System.IO.Compression.ZipFile]::ExtractToDirectory($msixPath.FullName, $msixExtractPath)\n        Copy-Item -Path (Join-Path -Path $msixExtractPath -ChildPath '*') -Destination $programDataWingetRoot -Recurse -Force\n        Write-WinGetWrapperLog -Message \"Bootstrapped WinGet to '$programDataWingetRoot'.\"\n    }\n\n    if (-not $isSystem) {\n        $userWingetExe = Get-UserWinGetExecutablePath\n        if (-not [string]::IsNullOrWhiteSpace($userWingetExe)) {\n            return $userWingetExe\n        }\n\n        if (Test-WinGetExecutable -Path $programDataWingetExe) {\n            return $programDataWingetExe\n        }\n\n        throw 'winget.exe could not be located for this user context. Ensure App Installer is installed for the signed-in user or pre-bootstrap WinGet in SYSTEM context.'\n    }\n\n    if (Test-WinGetExecutable -Path $programDataWingetExe) {\n        return $programDataWingetExe\n    }\n\n    Install-WinGetSystemBootstrap\n    if (Test-WinGetExecutable -Path $programDataWingetExe) {\n        return $programDataWingetExe\n    }\n\n    throw 'winget.exe could not be located or bootstrapped successfully for this context.'\n}\n\n$wingetCommand = 'winget install --id PuTTY.PuTTY --exact --silent --scope machine --accept-package-agreements --accept-source-agreements'\n$argumentString = ($wingetCommand -replace '^\\s*winget(?:\\.exe)?\\s*', '').Trim()\nif ([string]::IsNullOrWhiteSpace($argumentString)) {\n    throw \"Unable to derive WinGet arguments from command '$wingetCommand'.\"\n}\n\n$logDirectory = Get-HydrationWinGetLogDirectory\n$logFileName = Get-WinGetWrapperLogFileName\n$script:logPath = Join-Path -Path $logDirectory -ChildPath $logFileName\n$baseLogName = [System.IO.Path]::GetFileNameWithoutExtension($logFileName)\n$stdoutPath = Join-Path -Path $logDirectory -ChildPath \"$baseLogName.stdout.log\"\n$stderrPath = Join-Path -Path $logDirectory -ChildPath \"$baseLogName.stderr.log\"\n\nforeach ($streamPath in @($stdoutPath, $stderrPath)) {\n    if (Test-Path -Path $streamPath) {\n        Remove-Item -Path $streamPath -Force -ErrorAction SilentlyContinue\n    }\n}\n\nWrite-WinGetWrapperLog -Message \"Starting $operationName for package '$packageIdentifier'.\"\nWrite-WinGetWrapperLog -Message \"Resolved IME log path: $script:logPath\"\nWrite-WinGetWrapperLog -Message \"Executing WinGet command: $wingetCommand\"\n\ntry {\n    $wingetPath = Get-WinGetExecutablePath\n    Write-WinGetWrapperLog -Message \"Resolved winget executable: $wingetPath\"\n    $process = Start-Process -FilePath $wingetPath -ArgumentList $argumentString -Wait -PassThru -NoNewWindow -RedirectStandardOutput $stdoutPath -RedirectStandardError $stderrPath\n    Write-WinGetProcessStreamToLog -Path $stdoutPath -Label 'WinGet standard output'\n    Write-WinGetProcessStreamToLog -Path $stderrPath -Label 'WinGet standard error' -Level 'WARN'\n    $standardOutput = if (Test-Path -Path $stdoutPath) { @(Get-Content -Path $stdoutPath -ErrorAction SilentlyContinue) } else { @() }\n    $exitCode = [int]$process.ExitCode\n    Write-WinGetWrapperLog -Message \"WinGet process exited with code $exitCode.\"\n    if ($operationName -eq 'Install' -and ($exitCode -eq -1978335189 -or (Test-WinGetAlreadyInstalledNoUpgradeOutput -Output $standardOutput))) {\n        Write-WinGetWrapperLog -Message \"Package already installed (no upgrade needed). Treating as success.\" -Level 'INFO'\n        $exitCode = 0\n    }\n    exit $exitCode\n} catch {\n    Write-WinGetProcessStreamToLog -Path $stdoutPath -Label 'WinGet standard output'\n    Write-WinGetProcessStreamToLog -Path $stderrPath -Label 'WinGet standard error' -Level 'WARN'\n    Write-WinGetWrapperLog -Message \"Wrapper execution failed: $($_.Exception.Message)\" -Level 'ERROR'\n    throw\n}\n",
  "uninstallScriptContent": "$ErrorActionPreference = 'Stop'\n$packageIdentifier = 'PuTTY.PuTTY'\n$operationName = 'Uninstall'\n\nfunction Test-HydrationWinGetLogDirectory {\n    [CmdletBinding()]\n    param(\n        [Parameter(Mandatory)]\n        [string]$Path\n    )\n\n    if ([string]::IsNullOrWhiteSpace($Path)) {\n        return $false\n    }\n\n    try {\n        if (-not (Test-Path -Path $Path)) {\n            $null = New-Item -Path $Path -ItemType Directory -Force -ErrorAction Stop\n        }\n\n        $probePath = Join-Path -Path $Path -ChildPath (\"IntuneHydrationKit-LogProbe-$([guid]::NewGuid().ToString('N')).tmp\")\n        Set-Content -Path $probePath -Value '' -Encoding utf8 -ErrorAction Stop\n        Remove-Item -Path $probePath -Force -ErrorAction SilentlyContinue\n        return $true\n    } catch {\n        return $false\n    }\n}\n\nfunction Get-HydrationWinGetLogDirectory {\n    [CmdletBinding()]\n    param()\n\n    $programDataPath = if (-not [string]::IsNullOrWhiteSpace($env:ProgramData)) {\n        $env:ProgramData\n    } else {\n        'C:\\ProgramData'\n    }\n\n    $candidatePaths = [System.Collections.Generic.List[string]]::new()\n    $candidatePaths.Add((Join-Path -Path $programDataPath -ChildPath 'Microsoft\\IntuneManagementExtension\\Logs'))\n\n    if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {\n        $candidatePaths.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'IntuneHydrationKit\\Logs'))\n    }\n\n    if (-not [string]::IsNullOrWhiteSpace($env:TEMP)) {\n        $candidatePaths.Add((Join-Path -Path $env:TEMP -ChildPath 'IntuneHydrationKit\\Logs'))\n    }\n\n    $systemTempPath = [System.IO.Path]::GetTempPath()\n    if (-not [string]::IsNullOrWhiteSpace($systemTempPath)) {\n        $candidatePaths.Add((Join-Path -Path $systemTempPath -ChildPath 'IntuneHydrationKit\\Logs'))\n    }\n\n    $seenPaths = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)\n    foreach ($candidatePath in $candidatePaths) {\n        if ([string]::IsNullOrWhiteSpace($candidatePath) -or -not $seenPaths.Add($candidatePath)) {\n            continue\n        }\n\n        if (Test-HydrationWinGetLogDirectory -Path $candidatePath) {\n            return $candidatePath\n        }\n    }\n\n    throw 'No writable log directory was available for WinGet script execution.'\n}\n\nfunction Get-WinGetWrapperLogFileName {\n    [CmdletBinding()]\n    param()\n\n    $safePackageIdentifier = ($packageIdentifier -replace '[^A-Za-z0-9._-]+', '-').Trim('-')\n    if ([string]::IsNullOrWhiteSpace($safePackageIdentifier)) {\n        $safePackageIdentifier = 'package'\n    }\n\n    return \"IntuneHydrationKit-WinGet-$operationName-$safePackageIdentifier.log\"\n}\n\nfunction Write-WinGetWrapperLog {\n    [CmdletBinding()]\n    param(\n        [Parameter(Mandatory)]\n        [string]$Message,\n\n        [Parameter()]\n        [ValidateSet('INFO', 'WARN', 'ERROR')]\n        [string]$Level = 'INFO'\n    )\n\n    $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss.fff'\n    Add-Content -Path $script:logPath -Value \"`[$timestamp`] `[$Level`] $Message\"\n}\n\nfunction Write-WinGetProcessStreamToLog {\n    [CmdletBinding()]\n    param(\n        [Parameter(Mandatory)]\n        [string]$Path,\n\n        [Parameter(Mandatory)]\n        [string]$Label,\n\n        [Parameter()]\n        [ValidateSet('INFO', 'WARN', 'ERROR')]\n        [string]$Level = 'INFO'\n    )\n\n    if (-not (Test-Path -Path $Path)) {\n        return\n    }\n\n    $lines = @(Get-Content -Path $Path -ErrorAction SilentlyContinue)\n    if ($lines.Count -eq 0) {\n        return\n    }\n\n    Write-WinGetWrapperLog -Message \"${Label}:\" -Level $Level\n    foreach ($line in $lines) {\n        if ([string]::IsNullOrWhiteSpace($line)) {\n            continue\n        }\n\n        Write-WinGetWrapperLog -Message $line -Level $Level\n    }\n}\n\nfunction Test-WinGetAlreadyInstalledNoUpgradeOutput {\n    [CmdletBinding()]\n    param(\n        [Parameter()]\n        [string[]]$Output\n    )\n\n    $outputText = ($Output -join [Environment]::NewLine)\n    $foundExistingPackage = $outputText -match 'Found an existing package already installed\\. Trying to upgrade the installed package'\n    $noUpgradeAvailable = $outputText -match 'No available upgrade found' -or\n        $outputText -match 'No newer package versions are available'\n\n    return $foundExistingPackage -and $noUpgradeAvailable\n}\n\nfunction Get-WinGetExecutablePath {\n    [CmdletBinding()]\n    param()\n\n    $programDataRoot = if ([string]::IsNullOrWhiteSpace($env:ProgramData)) { 'C:\\ProgramData' } else { $env:ProgramData }\n    $programDataWingetRoot = Join-Path -Path $programDataRoot -ChildPath 'Microsoft.DesktopAppInstaller'\n    $programDataWingetExe = Join-Path -Path $programDataWingetRoot -ChildPath 'winget.exe'\n    $isSystem = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -eq 'NT AUTHORITY\\SYSTEM'\n\n    function Test-WinGetExecutable {\n        param(\n            [Parameter(Mandatory)]\n            [string]$Path\n        )\n\n        if (-not (Test-Path -Path $Path -PathType Leaf)) {\n            return $false\n        }\n\n        try {\n            $versionOutput = & $Path --version 2>&1\n            return $LASTEXITCODE -eq 0 -or $versionOutput -match 'v?\\d+\\.\\d+'\n        } catch {\n            return $false\n        }\n    }\n\n    function Get-UserWinGetExecutablePath {\n        [CmdletBinding()]\n        param()\n\n        $command = Get-Command -Name 'winget.exe' -ErrorAction SilentlyContinue\n        if ($command -and -not [string]::IsNullOrWhiteSpace($command.Source) -and (Test-WinGetExecutable -Path $command.Source)) {\n            return $command.Source\n        }\n\n        $searchPatterns = [System.Collections.Generic.List[string]]::new()\n\n        if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {\n            $searchPatterns.Add((Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\\WindowsApps\\winget.exe'))\n        }\n\n        if (-not [string]::IsNullOrWhiteSpace($env:ProgramFiles)) {\n            $searchPatterns.Add((Join-Path -Path $env:ProgramFiles -ChildPath 'WindowsApps\\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\\winget.exe'))\n        }\n\n        if (-not [string]::IsNullOrWhiteSpace(${env:ProgramFiles(x86)})) {\n            $searchPatterns.Add((Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'WindowsApps\\Microsoft.DesktopAppInstaller_*__8wekyb3d8bbwe\\winget.exe'))\n        }\n\n        foreach ($pattern in $searchPatterns) {\n            if ([string]::IsNullOrWhiteSpace($pattern)) {\n                continue\n            }\n\n            $candidateFiles = @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue | Sort-Object -Property FullName -Descending)\n            if ($candidateFiles.Count -gt 0 -and (Test-WinGetExecutable -Path $candidateFiles[0].FullName)) {\n                return $candidateFiles[0].FullName\n            }\n        }\n\n        return $null\n    }\n\n    function Install-WinGetSystemBootstrap {\n        [CmdletBinding()]\n        param()\n\n        function Get-AppInstallerMsixPath {\n            [CmdletBinding()]\n            param(\n                [Parameter(Mandatory)]\n                [string]$Path\n            )\n\n            foreach ($filter in @('AppInstaller*_x64*.msix', 'AppInstaller*.msix')) {\n                $msixPath = Get-ChildItem -Path $Path -Filter $filter -File -ErrorAction SilentlyContinue |\n                    Sort-Object -Property Name -Descending |\n                    Select-Object -First 1\n\n                if ($msixPath) {\n                    return $msixPath\n                }\n            }\n\n            throw 'Unable to locate App Installer MSIX payload inside the downloaded bundle.'\n        }\n\n        function Invoke-WinGetBootstrapDownload {\n            [CmdletBinding()]\n            param(\n                [Parameter(Mandatory)]\n                [string]$Uri,\n\n                [Parameter(Mandatory)]\n                [string]$OutFile\n            )\n\n            $downloadParams = @{\n                Uri        = $Uri\n                OutFile    = $OutFile\n                TimeoutSec = 120\n            }\n\n            if ($PSVersionTable.PSVersion.Major -lt 6) {\n                $downloadParams.UseBasicParsing = $true\n            }\n\n            Invoke-WebRequest @downloadParams\n        }\n\n        $tempRoot = [System.IO.Path]::GetTempPath()\n        if ([string]::IsNullOrWhiteSpace($tempRoot)) {\n            $tempRoot = if ([string]::IsNullOrWhiteSpace($env:TEMP)) { 'C:\\Windows\\Temp' } else { $env:TEMP }\n        }\n\n        $stagingRoot = Join-Path -Path $tempRoot -ChildPath 'IntuneHydrationKit-WinGetBootstrap'\n        $bundlePath = Join-Path -Path $stagingRoot -ChildPath 'Microsoft.DesktopAppInstaller.msixbundle'\n        $bundleExtractPath = Join-Path -Path $stagingRoot -ChildPath 'bundle'\n        $msixExtractPath = Join-Path -Path $stagingRoot -ChildPath 'appinstaller'\n        $vcRedistPath = Join-Path -Path $stagingRoot -ChildPath 'vc_redist.x64.exe'\n\n        Write-WinGetWrapperLog -Message 'Resolving WinGet for current execution context.'\n        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12\n        Add-Type -AssemblyName System.IO.Compression.FileSystem\n\n        if (Test-Path -Path $stagingRoot) {\n            Remove-Item -Path $stagingRoot -Recurse -Force -ErrorAction SilentlyContinue\n        }\n\n        foreach ($directoryPath in @($stagingRoot, $bundleExtractPath, $msixExtractPath)) {\n            $null = New-Item -Path $directoryPath -ItemType Directory -Force\n        }\n\n        try {\n            Invoke-WinGetBootstrapDownload -Uri 'https://aka.ms/vs/17/release/vc_redist.x64.exe' -OutFile $vcRedistPath\n            $vcRedist = Start-Process -FilePath $vcRedistPath -ArgumentList '/q /norestart' -Wait -PassThru\n            Write-WinGetWrapperLog -Message \"VC++ bootstrap exited with code $($vcRedist.ExitCode).\"\n        } catch {\n            Write-WinGetWrapperLog -Message \"VC++ bootstrap failed: $($_.Exception.Message)\" -Level 'WARN'\n        }\n\n        Invoke-WinGetBootstrapDownload -Uri 'https://aka.ms/getwinget' -OutFile $bundlePath\n        [System.IO.Compression.ZipFile]::ExtractToDirectory($bundlePath, $bundleExtractPath)\n        $msixPath = Get-AppInstallerMsixPath -Path $bundleExtractPath\n\n        if (Test-Path -Path $programDataWingetRoot) {\n            Remove-Item -Path $programDataWingetRoot -Recurse -Force -ErrorAction SilentlyContinue\n        }\n\n        $null = New-Item -Path $programDataWingetRoot -ItemType Directory -Force\n        [System.IO.Compression.ZipFile]::ExtractToDirectory($msixPath.FullName, $msixExtractPath)\n        Copy-Item -Path (Join-Path -Path $msixExtractPath -ChildPath '*') -Destination $programDataWingetRoot -Recurse -Force\n        Write-WinGetWrapperLog -Message \"Bootstrapped WinGet to '$programDataWingetRoot'.\"\n    }\n\n    if (-not $isSystem) {\n        $userWingetExe = Get-UserWinGetExecutablePath\n        if (-not [string]::IsNullOrWhiteSpace($userWingetExe)) {\n            return $userWingetExe\n        }\n\n        if (Test-WinGetExecutable -Path $programDataWingetExe) {\n            return $programDataWingetExe\n        }\n\n        throw 'winget.exe could not be located for this user context. Ensure App Installer is installed for the signed-in user or pre-bootstrap WinGet in SYSTEM context.'\n    }\n\n    if (Test-WinGetExecutable -Path $programDataWingetExe) {\n        return $programDataWingetExe\n    }\n\n    Install-WinGetSystemBootstrap\n    if (Test-WinGetExecutable -Path $programDataWingetExe) {\n        return $programDataWingetExe\n    }\n\n    throw 'winget.exe could not be located or bootstrapped successfully for this context.'\n}\n\n$wingetCommand = 'winget uninstall --id PuTTY.PuTTY --exact --scope machine --silent'\n$argumentString = ($wingetCommand -replace '^\\s*winget(?:\\.exe)?\\s*', '').Trim()\nif ([string]::IsNullOrWhiteSpace($argumentString)) {\n    throw \"Unable to derive WinGet arguments from command '$wingetCommand'.\"\n}\n\n$logDirectory = Get-HydrationWinGetLogDirectory\n$logFileName = Get-WinGetWrapperLogFileName\n$script:logPath = Join-Path -Path $logDirectory -ChildPath $logFileName\n$baseLogName = [System.IO.Path]::GetFileNameWithoutExtension($logFileName)\n$stdoutPath = Join-Path -Path $logDirectory -ChildPath \"$baseLogName.stdout.log\"\n$stderrPath = Join-Path -Path $logDirectory -ChildPath \"$baseLogName.stderr.log\"\n\nforeach ($streamPath in @($stdoutPath, $stderrPath)) {\n    if (Test-Path -Path $streamPath) {\n        Remove-Item -Path $streamPath -Force -ErrorAction SilentlyContinue\n    }\n}\n\nWrite-WinGetWrapperLog -Message \"Starting $operationName for package '$packageIdentifier'.\"\nWrite-WinGetWrapperLog -Message \"Resolved IME log path: $script:logPath\"\nWrite-WinGetWrapperLog -Message \"Executing WinGet command: $wingetCommand\"\n\ntry {\n    $wingetPath = Get-WinGetExecutablePath\n    Write-WinGetWrapperLog -Message \"Resolved winget executable: $wingetPath\"\n    $process = Start-Process -FilePath $wingetPath -ArgumentList $argumentString -Wait -PassThru -NoNewWindow -RedirectStandardOutput $stdoutPath -RedirectStandardError $stderrPath\n    Write-WinGetProcessStreamToLog -Path $stdoutPath -Label 'WinGet standard output'\n    Write-WinGetProcessStreamToLog -Path $stderrPath -Label 'WinGet standard error' -Level 'WARN'\n    $standardOutput = if (Test-Path -Path $stdoutPath) { @(Get-Content -Path $stdoutPath -ErrorAction SilentlyContinue) } else { @() }\n    $exitCode = [int]$process.ExitCode\n    Write-WinGetWrapperLog -Message \"WinGet process exited with code $exitCode.\"\n    if ($operationName -eq 'Install' -and ($exitCode -eq -1978335189 -or (Test-WinGetAlreadyInstalledNoUpgradeOutput -Output $standardOutput))) {\n        Write-WinGetWrapperLog -Message \"Package already installed (no upgrade needed). Treating as success.\" -Level 'INFO'\n        $exitCode = 0\n    }\n    exit $exitCode\n} catch {\n    Write-WinGetProcessStreamToLog -Path $stdoutPath -Label 'WinGet standard output'\n    Write-WinGetProcessStreamToLog -Path $stderrPath -Label 'WinGet standard error' -Level 'WARN'\n    Write-WinGetWrapperLog -Message \"Wrapper execution failed: $($_.Exception.Message)\" -Level 'ERROR'\n    throw\n}\n"
}