<# .SYNOPSIS "Windows 10 Sophia Script" is a PowerShell module for Windows 10 fine-tuning and automating the routine tasks Version: v5.3.3 Date: 20.01.2021 Copyright (c) 2021 farag & oZ-Zo Thanks to all https://forum.ru-board.com members involved .DESCRIPTION Supported Windows 10 versions: 2004 (20H1)/20H2 (2009), 19041/19042, Home/Pro/Enterprise, x64 Running the script is best done on a fresh install because running it on wrong tweaked system may result in errors occurring PowerShell must be run with elevated privileges Set execution policy to be able to run scripts only in the current PowerShell session: Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force .EXAMPLE PS C:\> .\Sophia.ps1 .NOTES https://forum.ru-board.com/topic.cgi?forum=62&topic=30617#15 https://habr.com/post/521202/ https://forums.mydigitallife.net/threads/powershell-script-setup-windows-10.81675/ https://www.reddit.com/r/PowerShell/comments/go2n5v/powershell_script_setup_windows_10/ .LINK https://github.com/farag2/Windows-10-Sophia-Script #> #region Checkings function Checkings { Set-StrictMode -Version Latest # Сlear the $Error variable # Очистка переменной $Error $Global:Error.Clear() # Detect the OS bitness # Определить разрядность ОС switch ([System.Environment]::Is64BitOperatingSystem) { $false { Write-Warning -Message $Localization.UnsupportedOSBitness exit } } # Detect the OS build version # Определить номер билда ОС switch ((Get-CimInstance -ClassName Win32_OperatingSystem).BuildNumber -ge 19041) { $false { Write-Warning -Message $Localization.UnsupportedOSBuild exit } } # Unblock all files in the folder by removing the Zone.Identifier alternate data stream with a value of "3" # Разблокировать все файлы в папке, удалив альтернативный потоки данных Zone.Identifier со значением "3" Get-ChildItem -Path $PSScriptRoot -Recurse -Force | Unblock-File -Confirm:$false # Import PowerShell 5.1 modules # Импорт модулей PowerShell 5.1 switch ($PSVersionTable.PSVersion.Major) { "7" { Import-Module -Name Microsoft.PowerShell.Management, PackageManagement, Appx -UseWindowsPowerShell } } # Turn off Controlled folder access to let the script proceed # Отключить контролируемый доступ к папкам switch ((Get-MpPreference).EnableControlledFolderAccess) { "1" { Write-Warning -Message $Localization.ControlledFolderAccessDisabled $Script:ControlledFolderAccess = $true Set-MpPreference -EnableControlledFolderAccess Disabled # Open "Ransomware protection" page # Открыть раздел "Защита от программ-шантажистов" Start-Process -FilePath windowsdefender://RansomwareProtection } "0" { $Script:ControlledFolderAccess = $false } } # Checking whether the current module version is the latest # Проверка: используется ли последняя версия модуля try { $LatestRelease = ((Invoke-RestMethod -Uri "https://api.github.com/repos/farag2/Windows-10-Sophia-Script/releases") | Where-Object -FilterScript {$_.prerelease -eq $false}).tag_name.Replace("v","")[0] $CurrentRelease = (Get-Module -Name Sophia).Version.ToString() switch ([System.Version]$LatestRelease -ne [System.Version]$CurrentRelease) { $true { Write-Warning -Message $Localization.UnsupportedRelease Start-Process -FilePath "https://github.com/farag2/Windows-10-Sophia-Script/releases/latest" exit } } } catch [System.Net.WebException] { Write-Warning -Message $Localization.NoInternetConnection Write-Error -Message $Localization.NoInternetConnection -ErrorAction SilentlyContinue } } #endregion Checkings <# Enable script logging. The log will be being recorded into the script folder To stop logging just close the console or type "Stop-Transcript" Включить логирование работы скрипта. Лог будет записываться в папку скрипта Чтобы остановить логгирование, закройте консоль или наберите "Stop-Transcript" #> function Logging { $TrascriptFilename = "Log-$((Get-Date).ToString("dd.MM.yyyy-HH-mm"))" Start-Transcript -Path $PSScriptRoot\$TrascriptFilename.txt -Force } # Create a restore point # Создать точку восстановления function CreateRestorePoint { if (-not (Get-ComputerRestorePoint)) { Enable-ComputerRestore -Drive $env:SystemDrive } # Never skip creating a restore point # Никогда не пропускать создание точек восстановления New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -Name SystemRestorePointCreationFrequency -PropertyType DWord -Value 0 -Force Checkpoint-Computer -Description "Windows 10 Sophia Script" -RestorePointType MODIFY_SETTINGS # Revert the System Restore checkpoint creation frequency to 1440 minutes # Вернуть частоту создания точек восстановления на 1440 минут New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -Name SystemRestorePointCreationFrequency -PropertyType DWord -Value 1440 -Force } #region Privacy & Telemetry <# .SYNOPSIS Disable/enable the DiagTrack service, firewall rule for Unified Telemetry Client Outbound Traffic and block connection Отключить/включить службу DiagTrack, правила брандмауэра для исходящего трафик клиента единой телеметрии и заблокировать соединение .PARAMETER Disable Disable the DiagTrack service, firewall rule for Unified Telemetry Client Outbound Traffic and block connection Отключить службу DiagTrack, правила брандмауэра для исходящего трафик клиента единой телеметрии и заблокировать соединение .PARAMETER Enable Enable the DiagTrack service, firewall rule for Unified Telemetry Client Outbound Traffic and allow connection Включить службу DiagTrack, правила брандмауэра для исходящего трафик клиента единой телеметрии и разрешить соединение .EXAMPLE DiagTrackService -Disable .EXAMPLE DiagTrackService -Enable .NOTES Current user only Только для текущего пользователя #> function DiagTrackService { param ( [Parameter( Mandatory = $true, ParameterSetName = "Enable" )] [switch] $Enable, [Parameter( Mandatory = $true, ParameterSetName = "Disable" )] [switch] $Disable ) switch ($PSCmdlet.ParameterSetName) { "Enable" { Get-Service -Name DiagTrack | Set-Service -StartupType Automatic Get-Service -Name DiagTrack | Start-Service # Enable firewall rule for Unified Telemetry Client Outbound Traffic and allow connection # Включить правила брандмауэра для исходящего трафика клиента единой телеметрии и разрешить соединение Get-NetFirewallRule -Group DiagTrack | Set-NetFirewallRule -Enabled True -Action Allow } "Disable" { Get-Service -Name DiagTrack | Stop-Service -Force Get-Service -Name DiagTrack | Set-Service -StartupType Disabled # Disable firewall rule for Unified Telemetry Client Outbound Traffic and block connection # Отключить правила брандмауэра для исходящего трафик клиента единой телеметрии и заблокировать соединение Get-NetFirewallRule -Group DiagTrack | Set-NetFirewallRule -Enabled False -Action Block } } } <# .SYNOPSIS Set the OS level of diagnostic data gathering to minimum/default Установить уровень сбора диагностических сведений ОС на минимальный/по умолчанию .PARAMETER Minimal Set the OS level of diagnostic data gathering to minimum Установить уровень сбора диагностических сведений ОС на минимальный .PARAMETER Default Set the OS level of diagnostic data gathering to minimum Установить уровень сбора диагностических сведений ОС на минимальный .EXAMPLE DiagnosticDataLevel -Minimal .EXAMPLE DiagnosticDataLevel -Default #> function DiagnosticDataLevel { param ( [Parameter( Mandatory = $true, ParameterSetName = "Minimal" )] [switch] $Minimal, [Parameter( Mandatory = $true, ParameterSetName = "Default" )] [switch] $Default ) switch ($PSCmdlet.ParameterSetName) { "Minimal" { if (Get-WindowsEdition -Online | Where-Object -FilterScript {$_.Edition -like "Enterprise*" -or $_.Edition -eq "Education"}) { # Optional diagnostic data # Необязательные диагностические данные New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 0 -Force } else { # Required diagnostic data # Обязательные диагностические данные New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 1 -Force } } "Default" { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 3 -Force } } } <# .SYNOPSIS Turn off/turn on Windows Error Reporting for the current user Отключить/включить отчеты об ошибках Windows для текущего пользователя .PARAMETER Disable Turn off Windows Error Reporting for the current user Отключить отчеты об ошибках Windows для текущего пользователя .PARAMETER Enable Turn on Windows Error Reporting for the current user Включить отчеты об ошибках Windows для текущего пользователя .EXAMPLE ErrorReporting -Disable .EXAMPLE ErrorReporting -Enable .NOTES Current user only Только для текущего пользователя #> function ErrorReporting { param ( [Parameter( Mandatory = $true, ParameterSetName = "Disable" )] [switch] $Disable, [Parameter( Mandatory = $true, ParameterSetName = "Enable" )] [switch] $Enable ) switch ($PSCmdlet.ParameterSetName) { "Disable" { if ((Get-WindowsEdition -Online).Edition -notmatch "Core*") { Get-ScheduledTask -TaskName QueueReporting | Disable-ScheduledTask New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\Windows Error Reporting" -Name Disabled -PropertyType DWord -Value 1 -Force } } "Enable" { Get-ScheduledTask -TaskName QueueReporting | Enable-ScheduledTask Remove-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\Windows Error Reporting" -Name Disabled -Force -ErrorAction SilentlyContinue } } } <# .SYNOPSIS Change Windows feedback frequency to "Never"/"Automatically" for the current user Изменить частоту формирования отзывов на "Никогда"/"Автоматически" для текущего пользователя .PARAMETER Disable Change Windows feedback frequency to "Never" for the current user Изменить частоту формирования отзывов на "Никогда" для текущего пользователя .PARAMETER Enable Change Windows feedback frequency to "Automatically" for the current user Изменить частоту формирования отзывов на "Автоматически" для текущего пользователя .EXAMPLE WindowsFeedback -Disable .EXAMPLE WindowsFeedback -Enable .NOTES Current user only Только для текущего пользователя #> function WindowsFeedback { param ( [Parameter( Mandatory = $true, ParameterSetName = "Disable" )] [switch] $Disable, [Parameter( Mandatory = $true, ParameterSetName = "Enable" )] [switch] $Enable ) switch ($PSCmdlet.ParameterSetName) { "Disable" { if (-not (Test-Path -Path HKCU:\SOFTWARE\Microsoft\Siuf\Rules)) { New-Item -Path HKCU:\SOFTWARE\Microsoft\Siuf\Rules -Force } New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Siuf\Rules -Name NumberOfSIUFInPeriod -PropertyType DWord -Value 0 -Force } "Enable" { Remove-Item -Path HKCU:\SOFTWARE\Microsoft\Siuf\Rules -Force -ErrorAction SilentlyContinue } } } <# .SYNOPSIS Turn off/turn on diagnostics tracking scheduled tasks Отключить/включить задачи диагностического отслеживания .PARAMETER Disable Turn off on diagnostics tracking scheduled tasks Отключить задачи диагностического отслеживания .PARAMETER Enable Turn on diagnostics tracking scheduled tasks Включить задачи диагностического отслеживания .EXAMPLE ScheduledTasks -Disable .EXAMPLE ScheduledTasks -Enable .NOTES A pop-up dialog box enables the user to select tasks Current user only Используется всплывающее диалоговое окно, позволяющее пользователю отмечать задачи Только для текущего пользователя Made by https://github.com/oz-zo #> function ScheduledTasks { param ( [Parameter( Mandatory = $true, ParameterSetName = "Enable" )] [switch] $Enable, [Parameter( Mandatory = $true, ParameterSetName = "Disable" )] [switch] $Disable ) Add-Type -AssemblyName PresentationCore, PresentationFramework #region Variables # Initialize an array list to store the scheduled tasks to remove # Создать массив задач для удаления $Tasks = New-Object -TypeName System.Collections.ArrayList($null) # The following tasks will have their checkboxes checked # Следующие задачи будут иметь чекбоксы отмеченными $CheckedScheduledTasks = @( # Collects program telemetry information if opted-in to the Microsoft Customer Experience Improvement Program # Собирает телеметрические данные программы при участии в Программе улучшения качества программного обеспечения Майкрософт "Microsoft Compatibility Appraiser", # Collects program telemetry information if opted-in to the Microsoft Customer Experience Improvement Program # Сбор телеметрических данных программы при участии в программе улучшения качества ПО "ProgramDataUpdater", # This task collects and uploads autochk SQM data if opted-in to the Microsoft Customer Experience Improvement Program # Эта задача собирает и загружает данные SQM при участии в программе улучшения качества программного обеспечения "Proxy", # If the user has consented to participate in the Windows Customer Experience Improvement Program, this job collects and sends usage data to Microsoft # Если пользователь изъявил желание участвовать в программе по улучшению качества программного обеспечения Windows, эта задача будет собирать и отправлять сведения о работе программного обеспечения в Майкрософт "Consolidator", # The USB CEIP (Customer Experience Improvement Program) task collects Universal Serial Bus related statistics and information about your machine and sends it to the Windows Device Connectivity engineering group at Microsoft # При выполнении задачи программы улучшения качества ПО шины USB (USB CEIP) осуществляется сбор статистических данных об использовании универсальной последовательной шины USB и с ведений о компьютере, которые направляются инженерной группе Майкрософт по вопросам подключения устройств в Windows "UsbCeip", # The Windows Disk Diagnostic reports general disk and system information to Microsoft for users participating in the Customer Experience Program # Для пользователей, участвующих в программе контроля качества программного обеспечения, служба диагностики дисков Windows предоставляет общие сведения о дисках и системе в корпорацию Майкрософт "Microsoft-Windows-DiskDiagnosticDataCollector", # Protects user files from accidental loss by copying them to a backup location when the system is unattended # Защищает файлы пользователя от случайной потери за счет их копирования в резервное расположение, когда система находится в автоматическом режиме "File History (maintenance mode)", # Measures a system's performance and capabilities # Измеряет быстродействие и возможности системы "WinSAT", # This task shows various Map related toasts # Эта задача показывает различные тосты (всплывающие уведомления) приложения "Карты" "MapsToastTask", # This task checks for updates to maps which you have downloaded for offline use # Эта задача проверяет наличие обновлений для карт, загруженных для автономного использования "MapsUpdateTask", # Initializes Family Safety monitoring and enforcement # Инициализация контроля и применения правил семейной безопасности "FamilySafetyMonitor", # Synchronizes the latest settings with the Microsoft family features service # Синхронизирует последние параметры со службой функций семьи учетных записей Майкрософт "FamilySafetyRefreshTask", # XblGameSave Standby Task "XblGameSaveTask" ) # If device is not a laptop disable FODCleanupTask too # Если устройство не является ноутбуком, отключить также и FODCleanupTask if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2) { # Windows Hello $CheckedScheduledTasks += "FODCleanupTask" } #endregion Variables #region XAML Markup # The section defines the design of the upcoming dialog box # Раздел, определяющий форму диалогового окна [xml]$XAML = '