From 8055e24fdeaf352071c67a3e5557205410fab1d5 Mon Sep 17 00:00:00 2001 From: Dmitry Nefedov <10544660+farag2@users.noreply.github.com> Date: Thu, 15 Oct 2020 21:54:47 +0300 Subject: [PATCH] Delete 2004.ps1 --- 4.x (outdated)/200x/2004.ps1 | 3591 ---------------------------------- 1 file changed, 3591 deletions(-) delete mode 100644 4.x (outdated)/200x/2004.ps1 diff --git a/4.x (outdated)/200x/2004.ps1 b/4.x (outdated)/200x/2004.ps1 deleted file mode 100644 index d34423c3..00000000 --- a/4.x (outdated)/200x/2004.ps1 +++ /dev/null @@ -1,3591 +0,0 @@ -<# -.SYNOPSIS - "Windows 10 Setup Script" is a set of tweaks for OS fine-tuning and automating the routine tasks - - Version: v4.6 - Date: 16.09.2020 - Copyright (c) 2020 farag & oZ-Zo - - Thanks to all http://forum.ru-board.com members involved - -.DESCRIPTION - Supported Windows 10 version: 2004 (20H1), 19041 build, x64 - Most of functions can be run also on LTSB/LTSC - - Tested on Home/Pro/Enterprise editions - - Due to the fact that the script includes about 150 functions, - you must read the entire script and comment out those sections that you do not want to be executed, - otherwise likely you will enable features that you do not want to be enabled - - Running the script is best done on a fresh install because running it on tweaked system may result in errors occurring - - Some third-party antiviruses flag this script or its' part as malicious one. This is a false positive due to $EncodedScript variable - You can read more about in "Create a task to clean up unused files and Windows updates in the Task Scheduler" section - You might need to disable tamper protection from your antivirus settings,re-enable it after running the script, and reboot - - Check whether the .ps1 file is encoded in UTF-8 with BOM - The script can not be executed via PowerShell ISE - 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:\> & '.\2004.ps1' - -.NOTES - Ask a question on - http://forum.ru-board.com/topic.cgi?forum=62&topic=30617#15 - https://habr.com/en/post/465365/ - https://4pda.ru/forum/index.php?s=&showtopic=523489&view=findpost&p=95909388 - 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-Setup-Script -#> - -#Requires -RunAsAdministrator -#Requires -Version 5.1 - -#region Check -Clear-Host - -# Get information about the current culture settings -# Получить сведения о параметрах текущей культуры -$RU = $PSUICulture -eq "ru-RU" - -# Detect the OS bitness -# Определить разрядность ОС -switch ([Environment]::Is64BitOperatingSystem) -{ - $false - { - if ($RU) - { - Write-Warning -Message "Скрипт поддерживает только Windows 10 x64" - } - else - { - Write-Warning -Message "The script supports Windows 10 x64 only" - } - break - } - Default {} -} - -# Detect the PowerShell bitness -# Определить разрядность PowerShell -switch ([IntPtr]::Size -eq 8) -{ - $false - { - if ($RU) - { - Write-Warning -Message "Скрипт поддерживает только PowerShell x64" - } - else - { - Write-Warning -Message "The script supports PowerShell x64 only" - } - break - } - Default {} -} - -# Detect whether the script is running via PowerShell ISE -# Определить, запущен ли скрипт в PowerShell ISE -if ($psISE) -{ - if ($RU) - { - Write-Warning -Message "Скрипт не может быть запущен в PowerShell ISE" - } - else - { - Write-Warning -Message "The script cannot be run via PowerShell ISE" - } - break -} -#endregion Check - -#region Begin -Set-StrictMode -Version Latest - -# Сlear $Error variable -# Очистка переменной $Error -$Error.Clear() - -# Create a restore point -# Создать точку восстановления -if ($RU) -{ - $Title = "Точка восстановления" - $Message = "Хотите включить защиту системы и создать точку восстановления?" - $Options = "&Создать", "&Не создавать", "&Пропустить" -} -else -{ - $Title = "Restore point" - $Message = "Would you like to enable System Restore and create a restore point?" - $Options = "&Create", "&Do not create", "&Skip" -} -$DefaultChoice = 2 -$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) - -switch ($Result) -{ - "0" - { - # Enable System Restore - # Включить функцию восстановления системы - if (-not (Get-ComputerRestorePoint)) - { - Enable-ComputerRestore -Drive $env:SystemDrive - } - - # Set system restore point creation frequency to 5 minutes - # Установить частоту создания точек восстановления на 5 минут - New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -Name SystemRestorePointCreationFrequency -PropertyType DWord -Value 5 -Force - Checkpoint-Computer -Description "Windows 10 Setup Script.ps1" -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 - } - "1" - { - if ($RU) - { - $Title = "Точки восстановления" - $Message = "Удалить все точки восстановления?" - $Options = "&Удалить", "&Пропустить" - } - else - { - $Title = "Restore point" - $Message = "Would you like to delete all System restore checkpoints?" - $Options = "&Delete", "&Skip" - } - $DefaultChoice = 1 - $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) - - switch ($Result) - { - "0" - { - # Delete all restore points - # Удалить все точки восстановения - Get-CimInstance -ClassName Win32_ShadowCopy | Remove-CimInstance - } - "1" - { - if ($RU) - { - Write-Verbose -Message "Пропущено" -Verbose - } - else - { - Write-Verbose -Message "Skipped" -Verbose - } - } - } - } - "2" - { - if ($RU) - { - Write-Verbose -Message "Пропущено" -Verbose - } - else - { - Write-Verbose -Message "Skipped" -Verbose - } - } -} -#endregion Begin - -#region Privacy & Telemetry -# Disable the "Connected User Experiences and Telemetry" service (DiagTrack) -# Отключить службу "Функциональные возможности для подключенных пользователей и телеметрия" (DiagTrack) -Get-Service -Name DiagTrack | Stop-Service -Force -Get-Service -Name DiagTrack | Set-Service -StartupType Disabled - -# Set the OS level of diagnostic data gathering to minimum -# Установить уровень сбора диагностических сведений ОС на минимальный -if (Get-WindowsEdition -Online | Where-Object -FilterScript {$_.Edition -like "Enterprise*" -or $_.Edition -eq "Education"}) -{ - # "Security" - # "Безопасность" - New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 0 -Force -} -else -{ - # "Basic" - # "Базовая настройка" - New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 1 -Force -} - -# Turn off Windows Error Reporting for the current user -# Отключить отчеты об ошибках Windows для текущего пользователя -if ((Get-WindowsEdition -Online).Edition -notmatch "Core*") -{ - New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\Windows Error Reporting" -Name Disabled -PropertyType DWord -Value 1 -Force -} - -# Change Windows feedback frequency to "Never" for the current user -# Изменить частоту формирования отзывов на "Никогда" для текущего пользователя -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 - -# Turn off diagnostics tracking scheduled tasks -# Отключить задачи диагностического отслеживания -$ScheduledTaskList = @( - # 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", - - # Windows Error Reporting task to process queued reports - # Задача отчетов об ошибках обрабатывает очередь отчетов - "QueueReporting", - - # 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 - $ScheduledTaskList += "FODCleanupTask" -} - -Get-ScheduledTask -TaskName $ScheduledTaskList | Disable-ScheduledTask - -# Do not use sign-in info to automatically finish setting up device and reopen apps after an update or restart (current user only) -# Не использовать данные для входа для автоматического завершения настройки устройства и открытия приложений после перезапуска или обновления (только для текущего пользователя) -$SID = (Get-CimInstance -ClassName Win32_UserAccount | Where-Object -FilterScript {$_.Name -eq $env:USERNAME}).SID -if (-not (Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\UserARSO\$SID")) -{ - New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\UserARSO\$SID" -Force -} -New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\UserARSO\$SID" -Name OptOut -PropertyType DWord -Value 1 -Force - -# Do not let websites provide locally relevant content by accessing language list (current user only) -# Не позволять веб-сайтам предоставлять местную информацию за счет доступа к списку языков (только для текущего пользователя) -New-ItemProperty -Path "HKCU:\Control Panel\International\User Profile" -Name HttpAcceptLanguageOptOut -PropertyType DWord -Value 1 -Force - -# Do not allow apps to use advertising ID (current user only) -# Не разрешать приложениям использовать идентификатор рекламы (только для текущего пользователя) -if (-not (Test-Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo)) -{ - New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo -Force -} -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo -Name Enabled -PropertyType DWord -Value 0 -Force - -# Do not let apps on other devices open and message apps on this device, and vice versa (current user only) -# Не разрешать приложениям на других устройствах запускать приложения и отправлять сообщения на этом устройстве и наоборот (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\CDP -Name RomeSdkChannelUserAuthzPolicy -PropertyType DWord -Value 0 -Force - -# Do not show the Windows welcome experiences after updates and occasionally when I sign in to highlight what's new and suggested (current user only) -# Не показывать экран приветствия Windows после обновлений и иногда при входе, чтобы сообщить о новых функциях и предложениях (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-310093Enabled -PropertyType DWord -Value 0 -Force - -# Get tip, trick, and suggestions as you use Windows (current user only) -# Получать советы, подсказки и рекомендации при использованию Windows (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338389Enabled -PropertyType DWord -Value 1 -Force - -# Do not show suggested content in the Settings app (current user only) -# Не показывать рекомендуемое содержимое в приложении "Параметры" (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338393Enabled -PropertyType DWord -Value 0 -Force -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-353694Enabled -PropertyType DWord -Value 0 -Force -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-353696Enabled -PropertyType DWord -Value 0 -Force - -# Turn off automatic installing suggested apps (current user only) -# Отключить автоматическую установку рекомендованных приложений (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SilentInstalledAppsEnabled -PropertyType DWord -Value 0 -Force - -# Do not suggest ways I can finish setting up my device to get the most out of Windows (current user only) -# Не предлагать способы завершения настройки устройства для максимально эффективного использования Windows (только для текущего пользователя) -if (-not (Test-Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\UserProfileEngagement)) -{ - New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\UserProfileEngagement -Force -} -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\UserProfileEngagement -Name ScoobeSystemSettingEnabled -PropertyType DWord -Value 0 -Force - -# Do not offer tailored experiences based on the diagnostic data setting (current user only) -# Не предлагать персонализированные возможности, основанные на выбранном параметре диагностических данных (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Privacy -Name TailoredExperiencesWithDiagnosticDataEnabled -PropertyType DWord -Value 0 -Force - -# Disable Bing search in the Start Menu -# Отключить в меню "Пуск" поиск через Bing -if ((Get-WinHomeLocation).GeoId -eq 244) -{ - if (-not (Test-Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer)) - { - New-Item -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Force - } - New-ItemProperty -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name DisableSearchBoxSuggestions -PropertyType DWord -Value 1 -Force -} -#endregion Privacy & Telemetry - -#region UI & Personalization -# Show "This PC" on Desktop (current user only) -# Отобразить "Этот компьютер" на рабочем столе (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -PropertyType DWord -Value 0 -Force - -# Do not use check boxes to select items (current user only) -# Не использовать флажки для выбора элементов (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name AutoCheckSelect -PropertyType DWord -Value 0 -Force - -# Show hidden files, folders, and drives (current user only) -# Показывать скрытые файлы, папки и диски (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name Hidden -PropertyType DWord -Value 1 -Force - -# Show file name extensions (current user only) -# Показывать расширения имён файлов (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideFileExt -PropertyType DWord -Value 0 -Force - -# Do not hide folder merge conflicts (current user only) -# Не скрывать конфликт слияния папок (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideMergeConflicts -PropertyType DWord -Value 0 -Force - -# Open File Explorer to: "This PC" (current user only) -# Открывать проводник для: "Этот компьютер" (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name LaunchTo -PropertyType DWord -Value 1 -Force - -# Do not show all folders in the navigation pane (current user only) -# Не отображать все папки в области навигации (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name NavPaneShowAllFolders -PropertyType DWord -Value 0 -Force - -# Do not show Cortana button on the taskbar (current user only) -# Не показывать кнопку Кортаны на панели задач (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowCortanaButton -PropertyType DWord -Value 0 -Force - -# Do not show sync provider notification within File Explorer (current user only) -# Не показывать уведомления поставщика синхронизации в проводнике (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSyncProviderNotifications -PropertyType DWord -Value 0 -Force - -# Do not show Task View button on the taskbar (current user only) -# Не показывать кнопку Просмотра задач (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowTaskViewButton -PropertyType DWord -Value 0 -Force - -# Do not show People button on the taskbar (current user only) -# Не показывать панель "Люди" на панели задач (только для текущего пользователя) -if (-not (Test-Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People)) -{ - New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People -Force -} -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People -Name PeopleBand -PropertyType DWord -Value 0 -Force - -# Show seconds on the taskbar clock (current user only) -# Отображать секунды в системных часах на панели задач (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSecondsInSystemClock -PropertyType DWord -Value 1 -Force - -# Do not show when snapping a window, what can be attached next to it (current user only) -# Не показывать при прикреплении окна, что можно прикрепить рядом с ним (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SnapAssist -PropertyType DWord -Value 0 -Force - -# Always open the file transfer dialog box in the detailed mode (current user only) -# Всегда открывать диалоговое окно передачи файлов в развернутом виде (только для текущего пользователя) -if (-not (Test-Path -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager)) -{ - New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager -Force -} -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager -Name EnthusiastMode -PropertyType DWord -Value 1 -Force - -# Show the ribbon expanded in File Explorer (current user only) -# Отображать ленту проводника в развернутом виде (только для текущего пользователя) -if (-not (Test-Path -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Ribbon)) -{ - New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Ribbon -Force -} -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Ribbon -Name MinimizedStateTabletModeOff -PropertyType DWord -Value 0 -Force - -<# -Display recycle bin files delete confirmation -Function [WinAPI.UpdateExplorer]::PostMessage() call required at the end - -Запрашивать подтверждение на удаление файлов в корзину -В конце необходим вызов функции [WinAPI.UpdateExplorer]::PostMessage() -#> -$ShellState = Get-ItemPropertyValue -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShellState -$ShellState[4] = 51 -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShellState -PropertyType Binary -Value $ShellState -Force - -# Hide the "3D Objects" folder from "This PC" and "Quick access" (current user only) -# Скрыть папку "Объемные объекты" из "Этот компьютер" и из панели быстрого доступа (только для текущего пользователя) -if (-not (Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FolderDescriptions\{31C0DD25-9439-4F12-BF41-7FF4EDA38722}\PropertyBag")) -{ - New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FolderDescriptions\{31C0DD25-9439-4F12-BF41-7FF4EDA38722}\PropertyBag" -Force -} -New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FolderDescriptions\{31C0DD25-9439-4F12-BF41-7FF4EDA38722}\PropertyBag" -Name ThisPCPolicy -PropertyType String -Value Hide -Force - -# Do not show frequently used folders in "Quick access" (current user only) -# Не показывать недавно используемые папки на панели быстрого доступа (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShowFrequent -PropertyType DWord -Value 0 -Force - -# Do not show recently used files in Quick access (current user only) -# Не показывать недавно использовавшиеся файлы на панели быстрого доступа (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShowRecent -PropertyType DWord -Value 0 -Force - -# Hide the search box or the search icon from the taskbar (current user only) -# Скрыть поле или значок поиска на панели задач (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search -Name SearchboxTaskbarMode -PropertyType DWord -Value 0 -Force - -# Do not show the "Windows Ink Workspace" button on the taskbar (current user only) -# Не показывать кнопку Windows Ink Workspace на панели задач (current user only) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\PenWorkspace -Name PenWorkspaceButtonDesiredVisibility -PropertyType DWord -Value 0 -Force - -# Always show all icons in the notification area (current user only) -# Всегда отображать все значки в области уведомлений (только для текущего пользователя) -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name EnableAutoTray -PropertyType DWord -Value 0 -Force - -# Unpin "Microsoft Edge" and "Microsoft Store" from the taskbar (current user only) -# Открепить Microsoft Edge и Microsoft Store от панели задач (только для текущего пользователя) -$Signature = @{ - Namespace = "WinAPI" - Name = "GetStr" - Language = "CSharp" - MemberDefinition = @" -// https://github.com/Disassembler0/Win10-Initial-Setup-Script/issues/8#issue-227159084 -[DllImport("kernel32.dll", CharSet = CharSet.Auto)] -public static extern IntPtr GetModuleHandle(string lpModuleName); -[DllImport("user32.dll", CharSet = CharSet.Auto)] -internal static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax); -public static string GetString(uint strId) -{ - IntPtr intPtr = GetModuleHandle("shell32.dll"); - StringBuilder sb = new StringBuilder(255); - LoadString(intPtr, strId, sb, sb.Capacity); - return sb.ToString(); -} -"@ -} -if (-not ("WinAPI.GetStr" -as [type])) -{ - Add-Type @Signature -Using System.Text -} - -# Extract the "Unpin from taskbar" string from shell32.dll -# Извлечь строку "Открепить от панели задач" из shell32.dll -$LocalizedString = [WinAPI.GetStr]::GetString(5387) -$Apps = (New-Object -ComObject Shell.Application).NameSpace("shell:::{4234d49b-0245-4df3-b780-3893943456e1}").Items() -$Apps | Where-Object -FilterScript {$_.Path -like "Microsoft.MicrosoftEdge*"} | ForEach-Object -Process {$_.Verbs() | Where-Object -FilterScript {$_.Name -eq $LocalizedString} | ForEach-Object -Process {$_.DoIt()}} -$Apps | Where-Object -FilterScript {$_.Path -like "Microsoft.WindowsStore*"} | ForEach-Object -Process {$_.Verbs() | Where-Object -FilterScript {$_.Name -eq $LocalizedString} | ForEach-Object -Process {$_.DoIt()}} - -# View the Control Panel icons by: large icons (current user only) -# Просмотр иконок Панели управления как: крупные значки (только для текущего пользователя) -if (-not (Test-Path -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel)) -{ - New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel -Force -} -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel -Name AllItemsIconView -PropertyType DWord -Value 0 -Force -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel -Name StartupPage -PropertyType DWord -Value 1 -Force - -# The color scheme for Windows shell (current user only) -# Режим цвета для Windows (только для текущего пользователя) -if ($RU) -{ - $Title = "Режим Windows" - $Message = "Установить цветовую схему Windows на светлую или темную" - $Options = "&Светлый", "&Темный", "&Пропустить" -} -else -{ - $Title = "Windows mode" - $Message = "Set the Windows color scheme to either Light or Dark" - $Options = "&Light", "&Dark", "&Skip" -} -$DefaultChoice = 1 -$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) - -switch ($Result) -{ - "0" - { - # Light color scheme - # Светлая цветовая схема - New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name SystemUsesLightTheme -PropertyType DWord -Value 1 -Force - } - "1" - { - # Dark color scheme - # Темная цветовая схема - New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name SystemUsesLightTheme -PropertyType DWord -Value 0 -Force - } - "2" - { - if ($RU) - { - Write-Verbose -Message "Пропущено" -Verbose - } - else - { - Write-Verbose -Message "Skipped" -Verbose - } - } -} - -# The color scheme for apps (current user only) -# Режим цвета для приложений (только для текущего пользователя) -if ($RU) -{ - $Title = "Режим приложений" - $Message = "Чтобы выбрать режим приложения по умолчанию, введите необходимую букву" - $Options = "&Светлый", "&Темный", "&Пропустить" -} -else -{ - $Title = "Apps mode" - $Message = "Set apps color scheme to either Light or Dark" - $Options = "&Light", "&Dark", "&Skip" -} -$DefaultChoice = 1 -$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) - -switch ($Result) -{ - "0" - { - # Light color scheme - # Светлый цветовая схема - New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -PropertyType DWord -Value 1 -Force - } - "1" - { - # Dark color scheme - # Темная цветовая схема - New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -PropertyType DWord -Value 0 -Force - } - "2" - { - if ($RU) - { - Write-Verbose -Message "Пропущено" -Verbose - } - else - { - Write-Verbose -Message "Skipped" -Verbose - } - } -} - -# Do not show the "New App Installed" indicator -# Не показывать уведомление "Установлено новое приложение" -if (-not (Test-Path -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer)) -{ - New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Force -} -New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name NoNewAppAlert -PropertyType DWord -Value 1 -Force - -# Do not show user first sign-in animation after the upgrade -# Не показывать анимацию при первом входе в систему после обновления -New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableFirstLogonAnimation -PropertyType DWord -Value 0 -Force - -# Set the quality factor of the JPEG desktop wallpapers to maximum (current user only) -# Установить коэффициент качества обоев рабочего стола в формате JPEG на максимальный (только для текущего пользователя) -New-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name JPEGImportQuality -PropertyType DWord -Value 100 -Force - -# Start Task Manager in expanded mode (current user only) -# Запускать Диспетчера задач в развернутом виде (только для текущего пользователя) -$Taskmgr = Get-Process -Name Taskmgr -ErrorAction Ignore -if ($Taskmgr) -{ - $Taskmgr.CloseMainWindow() -} - -Start-Process -FilePath Taskmgr.exe -WindowStyle Hidden -PassThru -do -{ - Start-Sleep -Milliseconds 100 - $Preferences = Get-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\TaskManager -Name Preferences -ErrorAction Ignore -} -until ($Preferences) -Stop-Process -Name Taskmgr - -$Preferences.Preferences[28] = 0 -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\TaskManager -Name Preferences -PropertyType Binary -Value $Preferences.Preferences -Force - -# Show a notification when your PC requires a restart to finish updating -# Показывать уведомление, когда компьютеру требуется перезагрузка для завершения обновления -New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name RestartNotificationsAllowed2 -PropertyType DWord -Value 1 -Force - -# Do not add the "- Shortcut" suffix to the file name of created shortcuts (current user only) -# Нe дoбaвлять "- яpлык" к имени coздaвaeмых яpлыков (только для текущего пользователя) -if (-not (Test-Path -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\NamingTemplates)) -{ - New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\NamingTemplates -Force -} -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\NamingTemplates -Name ShortcutNameTemplate -PropertyType String -Value "%s.lnk" -Force - -# Use the PrtScn button to open screen snipping (current user only) -# Использовать кнопку PRINT SCREEN, чтобы запустить функцию создания фрагмента экрана (только для текущего пользователя) -New-ItemProperty -Path "HKCU:\Control Panel\Keyboard" -Name PrintScreenKeyForSnippingEnabled -PropertyType DWord -Value 1 -Force - -# Enable the new style for the Start menu if the minimum version number is 19041.423. The style is scheduled for debut in Windows 10 version 20H2. -# Включить новый стиль Пуска, если номер билда минимум 19041.423. Релиз назначен на выход Windows 10 20H2. -if ((Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name UBR) -ge 423) -{ - if (-not (Test-Path -Path HKLM:\SYSTEM\CurrentControlSet\Control\FeatureManagement\Overrides\0\2093230218)) - { - New-Item -Path HKLM:\SYSTEM\CurrentControlSet\Control\FeatureManagement\Overrides\0\2093230218 -Force - } - New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FeatureManagement\Overrides\0\2093230218 -Name EnabledState -PropertyType DWORD -Value 2 -Force - New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FeatureManagement\Overrides\0\2093230218 -Name EnabledStateOptions -PropertyType DWORD -Value 0 -Force -} -#endregion UI & Personalization - -#region OneDrive -# Uninstall OneDrive -# Удалить OneDrive -[string]$UninstallString = Get-Package -Name "Microsoft OneDrive" -ProviderName Programs -ErrorAction Ignore | ForEach-Object -Process {$_.Meta.Attributes["UninstallString"]} -if ($UninstallString) -{ - if ($RU) - { - Write-Verbose -Message "Удаление OneDrive" -Verbose - } - else - { - Write-Verbose -Message "Uninstalling OneDrive" -Verbose - } - Stop-Process -Name OneDrive -Force -ErrorAction Ignore - Stop-Process -Name FileCoAuth -Force -ErrorAction Ignore - - # Save all opened folders in order to restore them after File Explorer restarting - # Сохранить все открытые папки, чтобы восстановить их после перезапуска проводника - Clear-Variable -Name OpenedFolders -Force -ErrorAction Ignore - $OpenedFolders = {(New-Object -ComObject Shell.Application).Windows() | ForEach-Object -Process {$_.Document.Folder.Self.Path}}.Invoke() - - # Getting link to the OneDriveSetup.exe and its' argument(s) - # Получаем ссылку на OneDriveSetup.exe и его аргумент(ы) - [string[]]$OneDriveSetup = ($UninstallString -Replace("\s*/",",/")).Split(",").Trim() - if ($OneDriveSetup.Count -eq 2) - { - Start-Process -FilePath $OneDriveSetup[0] -ArgumentList $OneDriveSetup[1..1] -Wait - } - else - { - Start-Process -FilePath $OneDriveSetup[0] -ArgumentList $OneDriveSetup[1..2] -Wait - } - Stop-Process -Name explorer -Force - - # Restoring closed folders - # Восстановляем закрытые папки - foreach ($OpenedFolder in $OpenedFolders) - { - if (Test-Path -Path $OpenedFolder) - { - Invoke-Item -Path $OpenedFolder - } - } - - # Getting the OneDrive user folder path - # Получаем путь до папки пользователя OneDrive - $OneDriveUserFolder = Get-ItemPropertyValue -Path HKCU:\Environment -Name OneDrive - if ((Get-ChildItem -Path $OneDriveUserFolder | Measure-Object).Count -eq 0) - { - Remove-Item -Path $OneDriveUserFolder -Recurse -Force - } - else - { - if ($RU) - { - Write-Error -Message "Папка $OneDriveUserFolder не пуста. Удалите ее вручную" -ErrorAction SilentlyContinue - } - else - { - Write-Error -Message "The $OneDriveUserFolder folder is not empty. Delete it manually" -ErrorAction SilentlyContinue - } - Invoke-Item -Path $OneDriveUserFolder - } - - Remove-ItemProperty -Path HKCU:\Environment -Name OneDrive, OneDriveConsumer -Force -ErrorAction Ignore - Remove-Item -Path HKCU:\SOFTWARE\Microsoft\OneDrive -Recurse -Force -ErrorAction Ignore - Remove-Item -Path HKLM:\SOFTWARE\WOW6432Node\Microsoft\OneDrive -Recurse -Force -ErrorAction Ignore - Remove-Item -Path "$env:ProgramData\Microsoft OneDrive" -Recurse -Force -ErrorAction Ignore - Remove-Item -Path $env:SystemDrive\OneDriveTemp -Recurse -Force -ErrorAction Ignore - Unregister-ScheduledTask -TaskName *OneDrive* -Confirm:$false - - # Getting the OneDrive folder path - # Получаем путь до папки OneDrive - $OneDriveFolder = Split-Path -Path (Split-Path -Path $OneDriveSetup[0] -Parent) - # Waiting for the FileSyncShell64.dll to be unloaded, using System.IO.File class - # Ожидаем, пока FileSyncShell64.dll выгрузится, используя класс System.IO.File - $FileSyncShell64dllFolder = Get-ChildItem -Path "$OneDriveFolder\*\amd64\FileSyncShell64.dll" -Force - foreach ($FileSyncShell64dll in $FileSyncShell64dllFolder) - { - do - { - try - { - $FileStream = [System.IO.File]::Open($FileSyncShell64dll.FullName,"Open","Write") - $FileStream.Close() - $FileStream.Dispose() - $Locked = $false - } - catch [System.UnauthorizedAccessException] - { - $Locked = $true - } - catch [Exception] - { - Start-Sleep -Milliseconds 500 - if ($RU) - { - Write-Verbose -Message "Ожидаем, пока $FileSyncShell64dll будет разблокирована" -Verbose - } - else - { - Write-Verbose -Message "Waiting for the $FileSyncShell64dll to be unlocked" -Verbose - } - } - } - while ($Locked) - } - - Remove-Item -Path $OneDriveFolder -Recurse -Force -ErrorAction Ignore - Remove-Item -Path $env:LOCALAPPDATA\OneDrive -Recurse -Force -ErrorAction Ignore - Remove-Item -Path $env:LOCALAPPDATA\Microsoft\OneDrive -Recurse -Force -ErrorAction Ignore - Remove-Item -Path "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\OneDrive.lnk" -Force -ErrorAction Ignore -} -#endregion OneDrive - -#region System -# Turn on Storage Sense (current user only) -# Включить Контроль памяти (только для текущего пользователя) -if (-not (Test-Path -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy)) -{ - New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -ItemType Directory -Force -} -New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 01 -PropertyType DWord -Value 1 -Force - -if ((Get-ItemPropertyValue -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 01) -eq "1") -{ - # Run Storage Sense every month (current user only) - # Запускать Контроль памяти каждый месяц (только для текущего пользователя) - New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 2048 -PropertyType DWord -Value 30 -Force - - # Delete temporary files that apps aren't using (current user only) - # Удалять временные файлы, не используемые в приложениях (только для текущего пользователя) - New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 04 -PropertyType DWord -Value 1 -Force - - # Delete files in recycle bin if they have been there for over 30 days (current user only) - # Удалять файлы из корзины, если они находятся в корзине более 30 дней (только для текущего пользователя) - New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 08 -PropertyType DWord -Value 1 -Force - New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 256 -PropertyType DWord -Value 30 -Force -} - -# Disable hibernation if the device is not a laptop -# Отключить режим гибернации, если устройство не является ноутбуком -if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2) -{ - POWERCFG /HIBERNATE OFF -} - -# Change the %TEMP% environment variable path to the %SystemDrive%\Temp (both machine-wide, and for the current user) -# Изменить путь переменной среды для %TEMP% на %SystemDrive%\Temp (для всех пользователей) -$Title = "" -if ($RU) -{ - $Message = "Изменить путь переменной среды для $env:TEMP на `"$env:SystemDrive\Temp`"?" - Write-Warning -Message "`nПеред выполнением закройте все работающие программы!" - $Options = "&Изменить", "&Пропустить" -} -else -{ - $Message = "Would you like to change the target of the $env:TEMP environment variable to the `"$env:SystemDrive\Temp`"?" - Write-Warning -Message "`nClose all running programs before proceeding!" - $Options = "&Change", "&Skip" -} -$DefaultChoice = 1 -$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) - -switch ($Result) -{ - "0" - { - if (-not (Test-Path -Path $env:SystemDrive\Temp)) - { - New-Item -Path $env:SystemDrive\Temp -ItemType Directory -Force - } - - [Environment]::SetEnvironmentVariable("TMP", "$env:SystemDrive\Temp", "User") - [Environment]::SetEnvironmentVariable("TMP", "$env:SystemDrive\Temp", "Machine") - [Environment]::SetEnvironmentVariable("TMP", "$env:SystemDrive\Temp", "Process") - New-ItemProperty -Path HKCU:\Environment -Name TMP -PropertyType ExpandString -Value %SystemDrive%\Temp -Force - - [Environment]::SetEnvironmentVariable("TEMP", "$env:SystemDrive\Temp", "User") - [Environment]::SetEnvironmentVariable("TEMP", "$env:SystemDrive\Temp", "Machine") - [Environment]::SetEnvironmentVariable("TEMP", "$env:SystemDrive\Temp", "Process") - New-ItemProperty -Path HKCU:\Environment -Name TEMP -PropertyType ExpandString -Value %SystemDrive%\Temp -Force - - New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name TMP -PropertyType ExpandString -Value %SystemDrive%\Temp -Force - New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name TEMP -PropertyType ExpandString -Value %SystemDrive%\Temp -Force - - # Restart the Printer Spooler service (Spooler) - # Перезапустить службу "Диспетчер печати" (Spooler) - Restart-Service -Name Spooler -Force - - Stop-Process -Name OneDrive -Force -ErrorAction Ignore - Stop-Process -Name FileCoAuth -Force -ErrorAction Ignore - - Remove-Item -Path $env:SystemRoot\Temp -Recurse -Force -ErrorAction Ignore - Remove-Item -Path $env:LOCALAPPDATA\Temp -Recurse -Force -ErrorAction Ignore - - # Create a symbolic link to the %SystemDrive%\Temp folder - # Создать символическую ссылку к папке %SystemDrive%\Temp - try - { - New-Item -Path $env:LOCALAPPDATA\Temp -ItemType SymbolicLink -Value $env:SystemDrive\Temp -Force - } - catch - { - if ($RU) - { - Write-Error -Message "Папка $env:LOCALAPPDATA\Temp не пуста. Очистите ее вручную" -ErrorAction SilentlyContinue - } - else - { - Write-Error -Message "The $env:LOCALAPPDATA\Temp folder is not empty. Clear it manually" -ErrorAction SilentlyContinue - } - Invoke-Item -Path $env:LOCALAPPDATA\Temp - } - } - "1" - { - if ($RU) - { - Write-Verbose -Message "Пропущено" -Verbose - } - else - { - Write-Verbose -Message "Skipped" -Verbose - } - } -} - -# Disable Windows 260 character path limit -# Отключить ограничение Windows на 260 символов в пути -New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled -PropertyType DWord -Value 1 -Force - -# Display the Stop error information on the BSoD -# Отображать Stop-ошибку при появлении BSoD -New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\CrashControl -Name DisplayParameters -PropertyType DWord -Value 1 -Force - -# Change "Behavior of the elevation prompt for administrators in Admin Approval Mode" to "Elevate without prompting" -# Изменить "Поведение запроса на повышение прав для администраторов в режиме одобрения администратором" на "Повышение прав без запроса" -New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -PropertyType DWord -Value 0 -Force - -# Turn on access to mapped drives from app running with elevated permissions with Admin Approval Mode enabled -# Включить доступ к сетевым дискам при включенном режиме одобрения администратором при доступе из программ, запущенных с повышенными правами -New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLinkedConnections -PropertyType DWord -Value 1 -Force - -# Opt out of the Delivery Optimization-assisted updates downloading -# Отказаться от загрузки обновлений с помощью оптимизации доставки -New-ItemProperty -Path Registry::HKEY_USERS\S-1-5-20\SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Settings -Name DownloadMode -PropertyType DWord -Value 0 -Force -Delete-DeliveryOptimizationCache -Force - -# Always wait for the network at computer startup and logon for workgroup networks -# Всегда ждать сеть при запуске и входе в систему для рабочих групп -if ((Get-CimInstance -ClassName CIM_ComputerSystem).PartOfDomain -eq $true) -{ - if (-not (Test-Path -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\CurrentVersion\Winlogon")) - { - New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\CurrentVersion\Winlogon" -Force - } - New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name SyncForegroundPolicy -PropertyType DWord -Value 1 -Force -} - -# Do not let Windows decide which printer should be the default one (current user only) -# Не разрешать Windows решать, какой принтер должен использоваться по умолчанию (только для текущего пользователя) -New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name LegacyDefaultPrinterMode -PropertyType DWord -Value 1 -Force - -# Disable the following Windows features -# Отключить следующие компоненты Windows -$WindowsOptionalFeatures = @( - # Legacy Components - # Компоненты прежних версий - "LegacyComponents", - - # Media Features - # Компоненты работы с мультимедиа - "MediaPlayback", - - # PowerShell 2.0 - "MicrosoftWindowsPowerShellV2", - "MicrosoftWindowsPowershellV2Root", - - # Microsoft XPS Document Writer - # Средство записи XPS-документов (Microsoft) - "Printing-XPSServices-Features", - - # Work Folders Client - # Клиент рабочих папок - "WorkFolders-Client" -) -Disable-WindowsOptionalFeature -Online -FeatureName $WindowsOptionalFeatures -NoRestart - -# Install the Windows Subsystem for Linux (WSL) -# Установить подсистему Windows для Linux (WSL) -# https://github.com/farag2/Windows-10-Setup-Script/issues/43 -if ($RU) -{ - $Title = "Windows Subsystem for Linux" - $Message = "Установить Windows Subsystem для Linux (WSL)?" - $Options = "&Установить", "&Пропустить" -} -else -{ - $Title = "Windows Subsystem for Linux" - $Message = "Would you like to install Windows Subsystem for Linux (WSL)?" - $Options = "&Install", "&Skip" -} -$DefaultChoice = 1 -$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) - -switch ($Result) -{ - "0" - { - $WSLFeatures = @( - # Enable the Windows Subsystem for Linux - # Включить подсистему Windows для Linux - "Microsoft-Windows-Subsystem-Linux", - - # Enable Virtual Machine Platform - # Включить поддержку платформы для виртуальных машин - "VirtualMachinePlatform" - ) - Enable-WindowsOptionalFeature -Online -FeatureName $WSLFeatures -NoRestart - - # Downloading the Linux kernel update package ### - # Скачиваем пакет обновления ядра Linux - try - { - [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 - if ((Invoke-WebRequest -Uri https://www.google.com -UseBasicParsing -DisableKeepAlive -Method Head).StatusDescription) - { - $Parameters = @{ - Uri = "https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi" - OutFile = "$PSScriptRoot\wsl_update_x64.msi" - Verbose = [switch]::Present - } - Invoke-WebRequest @Parameters - - Start-Process -FilePath $PSScriptRoot\wsl_update_x64.msi -ArgumentList "/passive" -Wait - Remove-Item -Path $PSScriptRoot\wsl_update_x64.msi -Force - } - } - catch - { - if ($Error.Exception.Status -eq "NameResolutionFailure") - { - if ($RU) - { - Write-Warning -Message "Отсутствует интернет-соединение" -ErrorAction SilentlyContinue - } - else - { - Write-Warning -Message "No Internet connection" -ErrorAction SilentlyContinue - } - } - } - } - "1" - { - if ($RU) - { - Write-Verbose -Message "Пропущено" -Verbose - } - else - { - Write-Verbose -Message "Skipped" -Verbose - } - } -} - -# Setup WSL -# Настроить WSL -# https://github.com/microsoft/WSL/issues/5437 -try -{ - # Set WSL 2 as a default version. Run the command only after restart - # Установить WSL 2 как версию по умолчанию. Выполните команду только после перезагрузки - wsl --set-default-version 2 - - # Configuring .wslconfig - # Настраиваем .wslconfig - if (-not (Test-Path -Path "$env:HOMEPATH\.wslconfig")) - { - $wslconfig = @" -[wsl2] -swap=0 -"@ - # Saving .wslconfig in UTF-8 encoding - # Сохраняем .wslconfig в кодировке UTF-8 - Set-Content -Path "$env:HOMEPATH\.wslconfig" -Value (New-Object System.Text.UTF8Encoding).GetBytes($wslconfig) -Encoding Byte -Force - } - else - { - $String = Get-Content -Path "$env:HOMEPATH\.wslconfig" | Select-String -Pattern "swap=" -SimpleMatch - if ($String) - { - (Get-Content -Path "$env:HOMEPATH\.wslconfig").Replace("swap=1", "swap=0") | Set-Content -Path "$env:HOMEPATH\.wslconfig" -Force - } - else - { - Add-Content -Path "$env:HOMEPATH\.wslconfig" -Value "`r`nswap=0" -Force - } - } -} -catch -{ - if ($RU) - { - Write-Warning -Message "Перезагрузите ПК и выполните`nwsl --set-default-version 2" -ErrorAction SilentlyContinue - Write-Error -Message "Перезагрузите ПК и выполните`nwsl --set-default-version 2" -ErrorAction SilentlyContinue - } - else - { - Write-Warning -Message "Restart PC and run`nwsl --set-default-version 2" -ErrorAction SilentlyContinue - Write-Error -Message "Restart PC and run`nwsl --set-default-version 2" -ErrorAction SilentlyContinue - } -} - -# Disable certain Feature On Demand v2 (FODv2) capabilities -# Отключить определенные компоненты "Функции по требованию" (FODv2) -Add-Type -AssemblyName PresentationCore, PresentationFramework - -#region Variables -# Initialize an array list to store the FODv2 items to remove -# Создать массив имен дополнительных компонентов для удаления -$Capabilities = New-Object -TypeName System.Collections.ArrayList($null) - -# The following FODv2 items will have their checkboxes checked, recommending the user to remove them -# Следующие дополнительные компоненты будут иметь чекбоксы отмеченными. Рекомендуются к удалению -$CheckedCapabilities = @( - # Steps Recorder - # Средство записи действий - "App.StepsRecorder*", - - # Microsoft Quick Assist - # Быстрая поддержка (Майкрософт) - "App.Support.QuickAssist*", - - # Windows Media Player - # Проигрыватель Windows Media - "Media.WindowsMediaPlayer*", - - # Microsoft Paint - "Microsoft.Windows.MSPaint*", - - # WordPad - "Microsoft.Windows.WordPad*", - - # Integrated faxing and scanning application for Windows - # Факсы и сканирование Windows - "Print.Fax.Scan*" -) -# If device is not a laptop disable "Hello.Face*" too -# Если устройство не является ноутбуком, отключить также и "Hello.Face" -if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2) -{ - # Windows Hello - $CheckedCapabilities += "Hello.Face*" -} - -# The following FODv2 items will be shown, but their checkboxes would be clear -# Следующие дополнительные компоненты будут видны, но их чекбоксы не будут отмечены -$ExcludedCapabilities = @( - # The DirectX Database to configure and optimize apps when multiple Graphics Adapters are present - # База данных DirectX для настройки и оптимизации приложений при наличии нескольких графических адаптеров - "DirectX\.Configuration\.Database", - - # Language components - # Языковые компоненты - "Language\.", - - # Notepad - # Блокнот - "Microsoft.Windows.Notepad*", - - # Mail, contacts, and calendar sync component - # Компонент синхронизации почты, контактов и календаря - "OneCoreUAP\.OneSync", - - # Management of printers, printer drivers, and printer servers - # Управление принтерами, драйверами принтеров и принт-серверами - "Print\.Management\.Console", - - # Features critical to Windows functionality - # Компоненты, критичные для работоспособности Windows - "Windows\.Client\.ShellComponents" -) -#endregion Variables - -#region XAML Markup -# The section defines the design of the upcoming dialog box -# Раздел, определяющий форму диалогового окна -[xml]$XAML = ' - - - - - - - - - - - - - - - -