# Import the Update Session COM object
$updateSession = New-Object -ComObject Microsoft.Update.Session

# Create an update searcher object
$updateSearcher = $updateSession.CreateUpdateSearcher()

# Search for available updates
$searchResult = $updateSearcher.Search("IsInstalled=0")

# Check if updates are available
if ($searchResult.Updates.Count -gt 0) {
    Write-Output "$($searchResult.Updates.Count) updates found. Installing..."

    # Create an update downloader object
    $updateDownloader = $updateSession.CreateUpdateDownloader()
    $updateDownloader.Updates = $searchResult.Updates

    # Download updates
    $downloadResult = $updateDownloader.Download()
    
    if ($downloadResult.ResultCode -eq 2) {
        Write-Output "Updates downloaded successfully."

        # Create an update installer object
        $updateInstaller = $updateSession.CreateUpdateInstaller()
        $updateInstaller.Updates = $searchResult.Updates

        # Install updates
        $installResult = $updateInstaller.Install()

        if ($installResult.ResultCode -eq 2) {
            Write-Output "Updates installed successfully."

            # Check if a restart is required
            if ($installResult.RebootRequired) {
                Write-Output "Restart is required. Restarting the computer..."
                Restart-Computer -Force
            } else {
                Write-Output "No restart is required."
            }
        } else {
            Write-Error "Failed to install updates. Result code: $($installResult.ResultCode)"
        }
    } else {
        Write-Error "Failed to download updates. Result code: $($downloadResult.ResultCode)"
    }
} else {
    Write-Output "No updates are available."
}
