<# : @echo off cd /d "%~dp0" powershell.exe -nol -nop -ex bypass -c "&{[ScriptBlock]::Create((gc -lit '%~f0' -enc UTF8) -join [Char]10).Invoke(@(&{$args}%*))}" exit /b #> # Без параметров: с заданным интервалом проверяет обновления, если есть - обновляет/устанавливает, # выдавая уведомление в трее, затем запускает Ungoogled # Параметры: # -onlyrun - не проверять обновления, сразу запуск хрома; # -onlycheck - наоборот, не запускать хром, только проверить обновления независимо от установленного интервала; # -lnk - создать ярлык на рабочем столе (если его еще нет) с запуском без параметров; # -ask - перед обновлением - спрашивать. # Интервал проверки обновлений (количество дней) задается в переменной $CheckInterval, имя папки профиля - $userdatadir, # список ключей запуска хрома - $argslist, файлы и папки, удаляемые после закрытия хрома - $udclean, $uddclean, # ветки реестра - $regclean. # Дата последней проверки обновлений хранится в переменной $lastcheck. [int]$CheckInterval = 1 $userdatadir = "UserData" $argslist = @( "--test-type=ui", "--popups-to-tabs", "--disable-logging", "--disable-breakpad", "--process-per-site", "--keep-old-history", "--disk-cache-size=1", "--enable-fast-unload", "--disable-machine-id", "--disable-encryption", "--remove-grab-handle", "--scroll-tabs=always", "--disk-cache-dir=nul", "--partitioned-cookies", "--disable-sharing-hub", "--disable-default-apps", "--enable-offline-pages", "--hide-sidepanel-button", "--allow-outdated-plugins", "--force-punycode-hostnames" "--remove-tabsearch-button", "--tab-hover-cards=tooltip", "--no-default-browser-check", "--show-avatar-button=never", "--disable-features=SidePanel", "--disable-account-consistency", "--disable-gpu-shader-disk-cache", "--disable-background-networking", "--enable-features=PasswordImport", "--user-data-dir=`"$userdatadir`"", "--allow-legacy-extension-manifests", "--close-window-with-last-tab=never", "--disable-search-engine-collection", "--disable-gpu-driver-bug-workarounds", "--enable-features=EncryptedClientHello", "--disable-features=UserAgentClientHint", "--partitioned-cookies-bypass-origin-trial", "--disable-features=PlatformHEVCDecoderSupport", "--disable-features=SettingsLandingPageRedesign", "--disable-features=AvoidEarlyExtensionScriptContextCreation", "--extension-mime-request-handling=always-prompt-for-install", "--disable-features=GlobalMediaControlsCastStartStop,GlobalMediaControlsModernUI" ) $udclean = @( "Crashpad", "SafetyTips", "Crowd Deny", "ZxcvbnData", "MEIPreload", "hyphen-data", "ShaderCache", "PKIMetadata", "OriginTrials", "GrShaderCache", "AutofillStates", "BrowserMetrics", "FileTypePolicies", "Module Info Cache", "SSLErrorAssistant", "OptimizationHints", "ClientSidePhishing", "Subresource Filter", "CertificateRevocation", "chrome_shutdown_ms.txt", "FirstPartySetsPreloaded", "OnDeviceHeadSuggestModel", "BrowserMetrics-spare.pma", "MediaFoundationWidevineCdm" ) $uddclean = @( "Cache", "GPUCache", "coupon_db", "DawnCache", "GCM Store", "IndexedDB", "Code Cache", "WidevineCdm", "Media Cache", "Pepper Data", "DailyBackup", "blob_storage", "Search Logos", "Service Worker", "BudgetDatabase", "shared_proto_db", "Session Storage", "VideoDecodeStats", "Download Service", "Application Cache", "Platform Notifications", "commerce_subscription_db", "JumpListIconsMostVisited", "JumpListIconsRecentClosed", "Feature Engagement Tracker", "data_reduction_proxy_leveldb", "OptimizationGuidePredictionModels", "optimization_guide_hint_cache_store", "optimization_guide_model_metadata_store" ) $regclean = "HKCU:Software\Chromium" $lastcheck = "11.07.2023" $batfilename = $MyInvocation.Line -match "\'(\w:\\.+)\'" | %{$matches[1]} $batfilepath = Split-path "$batfilename" if ($batfilepath -match "\w:\\$") {write-host "$batfilepath in root" -foregroundcolor red; return} $onlyrun = $args -match "^([/-]|--)?onlyrun$" $onlycheck = $args -match "^([/-]|--)?onlycheck$" $lnk = $args -match "^([/-]|--)?lnk$" $ask = $args -match "^([/-]|--)?ask$" Function RunChrome { if (-not([IO.File]::Exists("$batfilepath\chrome.exe"))) { Invoke-BalloonTip -Message "Missed chrome.exe" -MessageType "Error" SetLastCheck -date "01011970" return } Start-Process -FilePath "$batfilepath\chrome.exe" -ArgumentList $argslist -WorkingDirectory "$batfilepath" -Wait Get-Item -Path "$batfilepath\$userdatadir\*","$batfilepath\$userdatadir\Default\*" -Include $($udclean+$uddclean) | Remove-Item -Recurse -Force -ea 0 Remove-Item -Path $regclean -Recurse -Force -ErrorAction SilentlyContinue } [Net.ServicePointManager]::SecurityProtocol = 'ssl3,tls,tls11,tls12' [void] [System.Reflection.Assembly]::LoadWithPartialName('System.Web') [void] [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') Function Invoke-BalloonTip { [CmdletBinding()] Param ( [Parameter(Mandatory=$True)] [string]$Message, [Parameter()] [string]$Title="Ungoogled Chromium", [Parameter()] [System.Windows.Forms.ToolTipIcon]$MessageType="Info", [Parameter()] [string]$SysTrayIconPath=$( if ([IO.File]::Exists("$batfilepath\chrome.exe")) { "$batfilepath\chrome.exe" } else { "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" }), [Parameter()] [int]$Showtime=10000 ) $balloon = New-Object System.Windows.Forms.NotifyIcon [void](Register-ObjectEvent -InputObject $balloon -EventName MouseDoubleClick -SourceIdentifier IconClicked -Action { Write-Verbose 'Disposing of balloon' $balloon.dispose() Unregister-Event -SourceIdentifier IconClicked Remove-Job -Name IconClicked Remove-Variable -Name balloon }) $balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($SysTrayIconPath) $balloon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]$MessageType $balloon.BalloonTipText = $Message $balloon.BalloonTipTitle = $Title $balloon.Visible = $true $balloon.ShowBalloonTip($Showtime) Write-Verbose "Ending function" } Function SetLastCheck ($date) { Get-Content -Path "$batfilename" | %{ $_ -replace "(?<=\x24lastcheck\s*=\s*\x22)\d+","$date" } | Set-Content -Path "$($batfilename).tmp" Move-Item -Path "$($batfilename).tmp" -Destination "$batfilename" -Force } Function Check { try {$offsite = Invoke-RestMethod -Uri "https://api.github.com/repos/macchrome/winchrome/releases/latest"} catch {Invoke-BalloonTip -Message "Page is unavailable" -MessageType "Error"; return} $Script:latest = [version]($offsite.assets.browser_download_url | ?{ $_ -match ".+ungoogled-chromium-([\d\.]+)\S+Win64\.7z" } | Select -First 1 | %{$Script:distrlink = $matches[0]; $matches[1]}) if (-not($latest)) {Invoke-BalloonTip -Message "Error parsing page" -MessageType "Error"; return} SetLastCheck -date "$(Get-Date -Format 'dd.MM.yyyy')" $current = [version](Get-Item -Path "$batfilepath\chrome.exe" -ea 0).VersionInfo.ProductVersion if ($latest -le $current) {return} if ($ask) { if ( [System.Windows.Forms.MessageBox]::Show("Unggogled $latest is new version! Update?","Shooze action","YesNo","Question") -like 'Yes' ) { return $true } } else { Invoke-BalloonTip -Message "Unggogled $latest is new version, start update..." return $true } } Function Update { if ((ps chrome -ea 0).Path -eq "$batfilepath\chrome.exe") { Invoke-BalloonTip -Message "Unggogled is running" -MessageType "Error"; return } $Script:tmp = (New-Item -Path $("$batfilepath\"+"temp"+(get-random).tostring()) -ItemType Directory).FullName $distrname = $distrlink.split('/')[-1] try {Invoke-WebRequest -Uri "$distrlink" -OutFile "$tmp\$distrname"} catch {Invoke-BalloonTip -Message "Error download distr" -MessageType "Error"; return} try {Invoke-WebRequest -Uri "https://www.7-zip.org/a/7zr.exe" -OutFile "$tmp\7zr.exe"} catch {Invoke-BalloonTip -Message "Error download 7zip" -MessageType "Error"; return} &$tmp\7zr.exe x "$tmp\$distrname" -xr!"*er.exe" -o"$tmp" -y if ($LASTEXITCODE -ne 0) {Invoke-BalloonTip -Message "Error unpack" -MessageType "Error"; return} $nodel = "$userdatadir","$($tmp.split('\')[-1])","$($batfilename.split('\')[-1])" Get-Item -Path "$batfilepath\*" -Exclude $nodel -ea 0 | Remove-Item -Recurse -Force -ea 0 Copy-Item -Path "$tmp\ungoogl*\*" -Destination "$batfilepath" -Recurse -Force if ( -not ([IO.Directory]::Exists("$batfilepath\$userdatadir")) ) { New-Item -Path "$batfilepath\$userdatadir" -ItemType Directory -Force | Out-Null @( '{"distribution":{"alternate_shortcut_text":false,"chrome_shortcut_icon_index":0,"create_all_shortcuts":true,' '"do_not_create_desktop_shortcut":true,"do_not_create_quick_launch_shortcut":true,"do_not_create_taskbar_shortcut":true,' '"do_not_launch_chrome":true,"do_not_register_for_update_launch":true,"import_bookmarks":false,"import_history":false,' '"import_home_page":false,"import_search_engine":false,"make_chrome_default":false,"make_chrome_default_for_user":false,' '"show_welcome_page":false,"skip_first_run_ui":true,"system_level":false,"verbose_logging":false},' '"first_run_tabs":[],"homepage":"chrome://chrome-urls","homepage_is_newtabpage":false,"safebrowsing":{"enabled":false},' '"session":{"restore_on_startup":1},"alternate_error_pages":{"enabled":false},"NewTabPage":{"DisabledModules":["dummy","dummy2"],' '"ModulesVisible":false},"account_id_migration_state":2,"autofill":{"credit_card_enabled":false,"enabled":false,' '"orphan_rows_removed":true,"profile_enabled":false},"bookmark_bar":{"show_apps_shortcut":false,"show_on_all_tabs":false,' '"show_only_on_ntp":true,"show_reading_list":false},"browser":{"show_home_button":true,"check_default_browser":false,' '"clear_data":{"browsing_history_basic":true,"cache_basic":true,"cookies_basic":true,"form_data":true,"hosted_apps_data":true,' '"media_licenses":true,"passwords":true,"preferences_migrated_to_basic":true,"site_settings":true,"time_period":4,' '"time_period_basic":4},"clear_lso_data_enabled":true,"has_seen_welcome_page":true,"last_clear_browsing_data_tab":1,' '"window_placement":{"bottom":720,"left":64,"maximized":true,"right":1200,"top":32}},"credentials_enable_autosignin":false,' '"credentials_enable_service":false,"default_apps_install_state":2,"download":{"directory_upgrade":true,"prompt_for_download":true},' '"enable_do_not_track":true,"extensions":{"alerts":{"initialized":true},"ui":{"developer_mode":true}},' '"media":{"engagement":{"schema_version":4}},"net":{"network_prediction_options":2},"omnibox":{"prevent_url_elisions":true},' '"payments":{"can_make_payment_enabled":false},"profile":{"avatar_index":24,"block_third_party_cookies":true,' '"content_settings":{"clear_on_exit_migrated":true,"pref_version":1},' '"default_content_setting_values":{"background_sync":2,"cookies":1},' '"exit_type":"Normal","exited_cleanly":true,"local_avatar_index":24,' '"managed_user_id":"","name":"","password_manager_enabled":false},"search":{"suggest_enabled":false}}' ) -join '' | Set-Content -Path "$batfilepath\master_preferences" @( '{"background_mode":{"enabled":false},"browser":{"enabled_labs_experiments":["ignore-gpu-blocklist","smooth-scrolling@2"]},' '"hardware_acceleration_mode_previous":true,"profile":{"last_used":"Default"}}' ) -join '' | Set-Content -Path "$batfilepath\$userdatadir\Local State" } } if (-not($onlyrun)) { if ((ping -n 1 ya.ru) -match 'TTL=') { if ($onlycheck -or (New-TimeSpan -Start $([datetime]::parseexact($lastcheck, 'ddMMyyyy', $null))).Minutes -gt $CheckInterval) { if (Check) {Update; Remove-Item -Path "$tmp" -Recurse -Force -ErrorAction SilentlyContinue} } } else { Invoke-BalloonTip -Message "No internet connection" -MessageType "Error" } } if ($lnk) { if (-not([IO.File]::Exists("$env:USERPROFILE\Desktop\Ungoogled Chromium.lnk"))) { $lnkpath = Get-Item -Path "$env:USERPROFILE\Desktop\*.lnk" | %{ (New-Object -COM WScript.Shell).CreateShortcut($_) } | ?{$_.TargetPath -like "*powershell.exe*" -and $_.Arguments -like "*$batfilename*"} if ($lnkpath) {Invoke-BalloonTip -Message "Shortcut path already exists" -MessageType "Error"} elseif ([IO.File]::Exists("$batfilepath\chrome.exe")) { $shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut("$env:USERPROFILE\Desktop\Ungoogled Chromium.lnk") $shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" $shortcut.IconLocation = "$batfilepath\chrome.exe, 0" $shortcut.WindowStyle = 7 $shortcut.Arguments = "-NoProfile -WindowStyle Hidden -Command `"$batfilename`"" $shortcut.WorkingDirectory = "$batfilepath" $shortcut.Save() } else { Invoke-BalloonTip -Message "Shortcut not created, missed chrome.exe" -MessageType "Error" } } else { Invoke-BalloonTip -Message "Shortcut already exists" -MessageType "Error" } } if (-not($onlycheck)) { RunChrome } |