diff --git a/LTSC/Sophia.ps1 b/LTSC/Sophia.ps1
index bc97d1a9..7c42de55 100644
--- a/LTSC/Sophia.ps1
+++ b/LTSC/Sophia.ps1
@@ -1,2573 +1,1033 @@
<#
-.SYNOPSIS
- "Windows 10 Setup Script" is a set of tweaks for OS fine-tuning and automating the routine tasks
+ .SYNOPSIS
+ Default preset file for "Windows 10 Sophia Script" (LTSC version)
- Version: v4.5
- Date: 18.09.2020
+ Version: v5.0
+ Date: 29.12.2020
Copyright (c) 2020 farag & oZ-Zo
- Thanks to all http://forum.ru-board.com members involved
-
-.DESCRIPTION
- Supported Windows 10 version: 1809 Enterprise LTSC, 17763 build, x64
+ Thanks to all https://forum.ru-board.com members involved
- Due to the fact that the script includes about 140 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
+ .DESCRIPTION
+ Supported Windows 10 versions: 1809 Enterprise LTSC, 17763 build, x64
- Running the script is best done on a fresh install because running it on tweaked system may result in errors occurring
+ Due to the fact that the script includes more than 120 functions with different arguments, you must read the entire Sophia.ps1 carefully and
+ comment out/uncomment those functions that you do/do not want to be executed
+ Every tweak in the preset file has its' corresponding function to restore the default settings
- 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
+ Running the script is best done on a fresh install because running it on wrong tweaked system may result in errors occurring
- 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:\> & '.\LTSC.ps1'
+ .EXAMPLE
+ PS C:\> .\Sophia.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
+ .NOTES
+ https://forum.ru-board.com/topic.cgi?forum=62&topic=30617#15
+ https://habr.com/en/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-Setup-Script
+ .LINK
+ https://github.com/farag2/Windows-10-Sophia-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()
+$Host.UI.RawUI.WindowTitle = "Windows 10 Sophia Script for LTSC v5.0 | ©️ farag & oz-zo, 2015–2020 | $((Invoke-WebRequest -Uri https://wttr.in/?format=3 -UseBasicParsing).Content) | Happy New Year!"
+
+Remove-Module -Name Sophia -Force -ErrorAction Ignore
+Import-Module -Name $PSScriptRoot\Sophia.psd1 -PassThru -Force
+
+Import-LocalizedData -BindingVariable Global:Localization -FileName Sophia
+
+# Checkings
+# Проверки
+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"
+#>
+# Logging
# 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
+CreateRestorePoint
#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
+# Disable the "Connected User Experiences and Telemetry" service
+# Отключить службу "Функциональные возможности для подключенных пользователей и телеметрия"
+TelemetryService -Disable
+
+# Enable the "Connected User Experiences and Telemetry" service (default value)
+# Включить службу "Функциональные возможности для подключенных пользователей и телеметрия" (значение по умолчанию)
+# TelemetryService -Enable
# Set the OS level of diagnostic data gathering to minimum
# Установить уровень сбора диагностических сведений ОС на минимальный
-New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 0 -Force
+DiagnosticDataLevel -Minimal
+
+# Set the default OS level of diagnostic data gathering
+# Установить уровень сбора диагностических сведений ОС по умолчанию
+# DiagnosticDataLevel -Default
# Turn off Windows Error Reporting for the current user
# Отключить отчеты об ошибках Windows для текущего пользователя
-New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\Windows Error Reporting" -Name Disabled -PropertyType DWord -Value 1 -Force
+ErrorReporting -Disable
+
+# Turn on Windows Error Reporting for the current user (default value)
+# Включить отчеты об ошибках Windows для текущего пользователя (значение по умолчанию)
+# ErrorReporting -Enable
# 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
+WindowsFeedback -Disable
+
+# Change Windows Feedback frequency to "Automatically" for the current user (default value)
+# Изменить частоту формирования отзывов на "Автоматически" для текущего пользователя (значение по умолчанию)
+# WindowsFeedback -Enable
# 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",
+ScheduledTasks -Disable
- # 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
+# Turn on diagnostics tracking scheduled tasks (default value)
+# Включить задачи диагностического отслеживания (значение по умолчанию)
+# ScheduledTasks -Enable
# 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
+SigninInfo -Disable
+
+# Use sign-in info to automatically finish setting up device and reopen apps after an update or restart (current user only) (default value)
+# Использовать данные для входа для автоматического завершения настройки устройства и открытия приложений после перезапуска или обновления (только для текущего пользователя) (значение по умолчанию)
+# SigninInfo -Enable
# 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
+LanguageListAccess -Disable
+
+# Let websites provide locally relevant content by accessing language list (current user only) (default value)
+# Позволять веб-сайтам предоставлять местную информацию за счет доступа к списку языков (только для текущего пользователя) (значение по умолчанию)
+# LanguageListAccess -Enable
# 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
+AdvertisingID -Disable
+
+# Allow apps to use advertising ID (current user only) (default value)
+# Разрешать приложениям использовать идентификатор рекламы (только для текущего пользователя) (значение по умолчанию)
+# AdvertisingID -Enable
# 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
+ShareAcrossDevices -Disable
+
+# Let apps on other devices open and message apps on this device, and vice versa (current user only) (default value)
+# Разрешать приложениям на других устройствах запускать приложения и отправлять сообщения на этом устройстве и наоборот (только для текущего пользователя) (значение по умолчанию)
+# ShareAcrossDevices -Enable
#endregion Privacy & Telemetry
#region UI & Personalization
# Show "This PC" on Desktop (current user only)
# Отобразить "Этот компьютер" на рабочем столе (только для текущего пользователя)
-if (-not (Test-Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel))
-{
- New-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Force
-}
-New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -PropertyType DWord -Value 0 -Force
+ThisPC -Show
+
+# Hide "This PC" on Desktop (current user only) (default value)
+# Скрывать "Этот компьютер" на рабочем столе (только для текущего пользователя) (значение по умолчанию)
+# ThisPC -Hide
# 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
+CheckBoxes -Disable
+
+# Use check boxes to select items (current user only) (default value)
+# Использовать флажки для выбора элементов (только для текущего пользователя) (значение по умолчанию)
+# CheckBoxes -Enable
# 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
+# Отображать скрытые файлы, папки и диски (только для текущего пользователя)
+HiddenItems -Enable
+
+# Do not show hidden files, folders, and drives (current user only) (default value)
+# Не отображать скрытые файлы, папки и диски (только для текущего пользователя) (значение по умолчанию)
+# HiddenItems -Disable
# Show file name extensions (current user only)
-# Показывать расширения имён файлов (только для текущего пользователя)
-New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideFileExt -PropertyType DWord -Value 0 -Force
+# Отображать расширения имён файлов (только для текущего пользователя)
+FileExtensions -Show
+
+# Hide file name extensions (current user only) (default value)
+# Скрывать расширения имён файлов файлов (только для текущего пользователя) (значение по умолчанию)
+# FileExtensions -Hide
# 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
+MergeConflicts -Show
+
+# Hide folder merge conflicts (current user only) (default value)
+# Скрывать конфликт слияния папок (только для текущего пользователя) (значение по умолчанию)
+# MergeConflicts -Hide
# 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
+OpenFileExplorerTo -ThisPC
+
+# Open File Explorer to: "Quick access" (current user only) (default value)
+# Открывать проводник для: "Быстрый доступ" (только для текущего пользователя) (значение по умолчанию)
+# OpenFileExplorerTo -QuickAccess
+
+# Hide Task View button on the taskbar (current user only)
+# Скрывать кнопку Просмотра задач (только для текущего пользователя)
+TaskViewButton -Hide
-# 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
+# Show Task View button on the taskbar (current user only) (default value)
+# Показывать кнопку Просмотра задач (только для текущего пользователя) (значение по умолчанию)
+# TaskViewButton -Show
-# 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
+# Hide People button on the taskbar (current user only)
+# Скрывать панель "Люди" на панели задач (только для текущего пользователя)
+PeopleTaskbar -Hide
-# 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 People button on the taskbar (current user only) (default value)
+# Показывать панель "Люди" на панели задач (только для текущего пользователя) (значение по умолчанию)
+# PeopleTaskbar -Show
# 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
+SecondsInSystemClock -Show
-# 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
+# Hide seconds on the taskbar clock (current user only) (default value)
+# Скрывать секунды в системных часах на панели задач (только для текущего пользователя) (значение по умолчанию)
+# SecondsInSystemClock -Hide
+
+# When I snap a window, do not show what I can snap next to it (current user only)
+# При прикреплении окна не показывать, что можно прикрепить рядом с ним (только для текущего пользователя)
+SnapAssist -Disable
+
+# When I snap a window, show what I can snap next to it (current user only) (default value)
+# При прикреплении окна не показывать/показывать, что можно прикрепить рядом с ним (только для текущего пользователя) (значение по умолчанию)
+# SnapAssist -Enable
# 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
+FileTransferDialog -Detailed
-<#
-Display recycle bin files delete confirmation
-Function [WinAPI.UpdateExplorer]::PostMessage() call required at the end
+# Always open the file transfer dialog box in the compact mode (current user only) (default value)
+# Всегда открывать диалоговое окно передачи файлов в свернутом виде (только для текущего пользователя) (значение по умолчанию)
+# FileTransferDialog -Compact
-Запрашивать подтверждение на удаление файлов в корзину
-В конце необходим вызов функции [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
+# Always expand the ribbon in the File Explorer (current user only)
+# Всегда разворачивать ленту в проводнике (только для текущего пользователя)
+FileExplorerRibbon -Expanded
+
+# Always minimize the ribbon in the File Explorer (current user only) (default value)
+# Не отображать ленту проводника в развернутом виде (только для текущего пользователя) (значение по умолчанию)
+# FileExplorerRibbon -Minimized
+
+# Display recycle bin files delete confirmation
+# Запрашивать подтверждение на удаление файлов в корзину
+RecycleBinDeleteConfirmation -Enable
+
+# Do not display recycle bin files delete confirmation (default value)
+# Не запрашивать подтверждение на удаление файлов в корзину (значение по умолчанию)
+# RecycleBinDeleteConfirmation -Disable
+
+# Hide the "3D Objects" folder in "This PC" and "Quick access" (current user only)
+# Скрыть папку "Объемные объекты" в "Этот компьютер" и панели быстрого доступа (только для текущего пользователя)
+3DObjects -Hide
+
+# Show the "3D Objects" folder in "This PC" and "Quick access" (current user only) (default value)
+# Отобразить папку "Объемные объекты" в "Этот компьютер" и панели быстрого доступа (только для текущего пользователя) (значение по умолчанию)
+# 3DObjects -Show
+
+# Hide frequently used folders in "Quick access" (current user only)
+# Скрыть недавно используемые папки на панели быстрого доступа (только для текущего пользователя)
+QuickAccessFrequentFolders -Hide
+
+# Show frequently used folders in "Quick access" (current user only) (default value)
+# Показывать недавно используемые папки на панели быстрого доступа (только для текущего пользователя) (значение по умолчанию)
+# QuickAccessFrequentFolders -Show
# 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
+QuickAccessRecentFiles -Hide
+
+# Show recently used files in Quick access (current user only) (default value)
+# Показывать недавно использовавшиеся файлы на панели быстрого доступа (только для текущего пользователя) (значение по умолчанию)
+# QuickAccessRecentFiles -Show
# 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
+TaskbarSearch -Hide
+
+# Show the search box on the taskbar (current user only)
+# Показать поле поиска на панели задач (только для текущего пользователя)
+# TaskbarSearch -SearchIcon
+
+# Show the search icon on the taskbar (current user only) (default value)
+# Показать поле поиска на панели задач (только для текущего пользователя) (значение по умолчанию)
+# TaskbarSearch -SearchBox
# 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
+TrayIcons -Show
+
+# Do not show all icons in the notification area (current user only) (default value)
+# Не отображать все значки в области уведомлений (только для текущего пользователя) (значение по умолчанию)
+# TrayIcons -Hide
# 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
- }
- }
-}
+ControlPanelView -LargeIcons
+
+# View the Control Panel icons by: category (current user only) (default value)
+# Просмотр значки Панели управления как "категория" (только для текущего пользователя) (значение по умолчанию)
+# ControlPanelView -Category
+
+# Set the Windows mode color scheme to the dark (current user only)
+# Установить цвет режима Windows по умолчанию на темный (только для текущего пользователя)
+WindowsColorScheme -Dark
+
+# Set the Windows mode color scheme to the light (current user only)
+# Установить режим цвета для Windows на светлый (только для текущего пользователя)
+# WindowsColorScheme -Light
+
+# Set the default app mode color scheme to the dark (current user only)
+# Установить цвет режима приложений по умолчанию на темный (только для текущего пользователя)
+AppMode -Dark
+
+# Set the default app mode color scheme to the light (current user only)
+# Установить цвет режима приложений по умолчанию на светлый (только для текущего пользователя)
+# AppMode -Light
# 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
+NewAppInstalledNotification -Hide
-# 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
+# Show the "New App Installed" indicator (default value)
+# Показывать уведомление "Установлено новое приложение" (значение по умолчанию)
+# NewAppInstalledNotification -Show
+
+# Hide user first sign-in animation after the upgrade
+# Скрывать анимацию при первом входе в систему после обновления
+FirstLogonAnimation -Disable
+
+# Show user first sign-in animation after the upgrade (default value)
+# Показывать анимацию при первом входе в систему после обновления (значение по умолчанию)
+# FirstLogonAnimation -Enable
# 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
+JPEGWallpapersQuality -Max
+
+# Set the quality factor of the JPEG desktop wallpapers to default (current user only)
+# Установить коэффициент качества обоев рабочего стола в формате JPEG по умолчанию (только для текущего пользователя)
+# JPEGWallpapersQuality -Default
# 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
+TaskManagerWindow -Expanded
+
+# Start Task Manager in compact mode (current user only) (default value)
+# Запускать Диспетчера задач в свернутом виде (только для текущего пользователя) (значение по умолчанию)
+# TaskManagerWindow -Compact
# 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
+RestartNotification -Show
+
+# Do not show a notification when your PC requires a restart to finish updating (default value)
+# Не показывать уведомление, когда компьютеру требуется перезагрузка для завершения обновления (значение по умолчанию)
+# RestartNotification -Hide
# 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
+ShortcutsSuffix -Disable
+
+# Add the "- Shortcut" suffix to the file name of created shortcuts (current user only) (default value)
+# Дoбaвлять "- яpлык" к имени coздaвaeмых яpлыков (только для текущего пользователя) (значение по умолчанию)
+# ShortcutsSuffix -Enable
# 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
+PrtScnSnippingTool -Enable
+
+# Do not use the PrtScn button to open screen snipping (current user only) (default value)
+# Не использовать кнопку PRINT SCREEN, чтобы запустить функцию создания фрагмента экрана (только для текущего пользователя) (значение по умолчанию)
+# PrtScnSnippingTool -Disable
+
+# Let me use a different input method for each app window (current user only)
+# Позволить выбирать метод ввода для каждого окна (только для текущего пользователя)
+AppsLanguageSwitch -Disable
+
+# Do not let use a different input method for each app window (current user only) (default value)
+# Не позволять выбирать метод ввода для каждого окна (только для текущего пользователя) (значение по умолчанию)
+# AppsLanguageSwitch -Enable
#endregion UI & Personalization
#region System
+#region StorageSense
# 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
-}
+StorageSense -Enable
+
+# Turn off Storage Sense (current user only) (default value)
+# Выключить Контроль памяти (только для текущего пользователя) (значение по умолчанию)
+# StorageSense -Disable
+
+# Run Storage Sense every month (current user only)
+# Запускать Контроль памяти каждый месяц (только для текущего пользователя)
+StorageSenseFrequency -Month
+
+# Run Storage Sense during low free disk space (default value) (current user only)
+# Запускать Контроль памяти, когда остается мало место на диске (значение по умолчанию) (только для текущего пользователя)
+# StorageSenseFrequency -Default
+
+# Delete temporary files that apps aren't using (current user only)
+# Удалять временные файлы, не используемые в приложениях (только для текущего пользователя)
+StorageSenseTempFiles -Enable
+
+# Do not delete temporary files that apps aren't using (current user only)
+# Не удалять временные файлы, не используемые в приложениях (только для текущего пользователя)
+# StorageSenseTempFiles -Disable
+
+# Delete files in recycle bin if they have been there for over 30 days (current user only)
+# Удалять файлы из корзины, если они находятся в корзине более 30 дней (только для текущего пользователя)
+StorageSenseRecycleBin -Enable
+
+# Do not delete files in recycle bin if they have been there for over 30 days (current user only)
+# Не удалять файлы из корзины, если они находятся в корзине более 30 дней (только для текущего пользователя)
+# StorageSenseRecycleBin -Disable
+#endregion StorageSense
# 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
+Hibernate -Disable
+
+# Enable hibernate (default value)
+# Включить режим гибернации (значение по умолчанию)
+# Hibernate -Enable
+
+# Change the %TEMP% environment variable path to "%SystemDrive%\Temp" (both machine-wide, and for the current user)
+# Изменить путь переменной среды для %TEMP% на "%SystemDrive%\Temp" (для всех пользователей)
+# TempFolder -SystemDrive
+
+# Change %TEMP% environment variable path to "%LOCALAPPDATA%\Temp" (both machine-wide, and for the current user) (default value)
+# Изменить путь переменной среды для %TEMP% на "LOCALAPPDATA%\Temp" (для всех пользователей) (значение по умолчанию)
+# TempFolder -Default
+
+# Disable Windows 260 characters path limit
# Отключить ограничение Windows на 260 символов в пути
-New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled -PropertyType DWord -Value 1 -Force
+Win32LongPathLimit -Disable
+
+# Enable Windows 260 character path limit (default value)
+# Включить ограничение Windows на 260 символов в пути (значение по умолчанию)
+# Win32LongPathLimit -Enable
# 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
+BSoDStopError -Enable
+
+# Do not display the Stop error information on the BSoD (default value)
+# Не отображать Stop-ошибку при появлении BSoD (значение по умолчанию)
+# BSoDStopError -Disable
# 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
+AdminApprovalMode -Disable
+
+# Change "Behavior of the elevation prompt for administrators in Admin Approval Mode" to "Prompt for consent for non-Windows binaries" (default value)
+# Изменить "Поведение запроса на повышение прав для администраторов в режиме одобрения администратором" на "Запрос согласия для исполняемых файлов, отличных от Windows" (значение по умолчанию)
+# AdminApprovalMode -Enable
# 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
+MappedDrivesAppElevatedAccess -Enable
+
+# Turn off access to mapped drives from app running with elevated permissions with Admin Approval Mode enabled (default value)
+# Выключить доступ к сетевым дискам при включенном режиме одобрения администратором при доступе из программ, запущенных с повышенными правами (значение по умолчанию)
+# MappedDrivesAppElevatedAccess -Disable
# 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
+DeliveryOptimization -Disable
+
+# Opt-in to the Delivery Optimization-assisted updates downloading (default value)
+# Включить загрузку обновлений с помощью оптимизации доставки (значение по умолчанию)
+# DeliveryOptimization -Enable
# 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
-}
+WaitNetworkStartup -Enable
+
+# Never wait for the network at computer startup and logon for workgroup networks (default value)
+# Никогда не ждать сеть при запуске и входе в систему для рабочих групп (значение по умолчанию)
+# WaitNetworkStartup -Disable
# 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
-
-# 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*",
-
- # 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\.",
-
- # Mail, contacts, and calendar sync component
- # Компонент синхронизации почты, контактов и календаря
- "OneCoreUAP\.OneSync"
-)
-#endregion Variables
-
-#region XAML Markup
-# The section defines the design of the upcoming dialog box
-# Раздел, определяющий форму диалогового окна
-[xml]$XAML = '
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-'
-#endregion XAML Markup
-
-$Reader = (New-Object -TypeName System.Xml.XmlNodeReader -ArgumentList $XAML)
-$Form = [Windows.Markup.XamlReader]::Load($Reader)
-$XAML.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | ForEach-Object -Process {
- Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name) -Scope Global
-}
-
-#region Functions
-function Get-CheckboxClicked
-{
- [CmdletBinding()]
- param
- (
- [Parameter(
- Mandatory = $true,
- ValueFromPipeline = $true
- )]
- [ValidateNotNull()]
- $CheckBox
- )
-
- $Capability = $CheckBox.Parent.Children[1].Text
- if ($CheckBox.IsChecked)
- {
- [void]$Capabilities.Add($Capability)
- }
- else
- {
- [void]$Capabilities.Remove($Capability)
- }
- if ($Capabilities.Count -gt 0)
- {
- $Button.IsEnabled = $true
- }
- else
- {
- $Button.IsEnabled = $false
- }
-}
-
-function DeleteButton
-{
- [void]$Window.Close()
- $OFS = "|"
- Get-WindowsCapability -Online | Where-Object -FilterScript {$_.Name -cmatch $Capabilities} | Remove-WindowsCapability -Online
- $OFS = " "
-}
-
-function Add-CapabilityControl
-{
- [CmdletBinding()]
- param
- (
- [Parameter(
- Mandatory = $true,
- ValueFromPipeline = $true
- )]
- [ValidateNotNull()]
- [string]
- $Capability
- )
-
- $CheckBox = New-Object -TypeName System.Windows.Controls.CheckBox
- $CheckBox.Add_Click({Get-CheckboxClicked -CheckBox $_.Source})
-
- $TextBlock = New-Object -TypeName System.Windows.Controls.TextBlock
- $TextBlock.Text = $Capability
-
- $StackPanel = New-Object -TypeName System.Windows.Controls.StackPanel
- [void]$StackPanel.Children.Add($CheckBox)
- [void]$StackPanel.Children.Add($TextBlock)
-
- [void]$PanelContainer.Children.Add($StackPanel)
-
- $CheckBox.IsChecked = $false
-
- if ($CheckedCapabilities | Where-Object -FilterScript {$Capability -like $_})
- {
- $CheckBox.IsChecked = $true
- # If capability checked, add to the array list to remove
- # Если пакет выделен, то добавить в массив для удаления
- [void]$Capabilities.Add($Capability)
- }
-}
-#endregion Functions
-
-#region Events Handlers
-# Window Loaded Event
-$Window.Add_Loaded({
- $OFS = "|"
- (Get-WindowsCapability -Online | Where-Object -FilterScript {($_.State -eq "Installed") -and ($_.Name -cnotmatch $ExcludedCapabilities)}).Name | ForEach-Object -Process {
- Add-CapabilityControl -Capability $_
- }
- $OFS = " "
-
- if ($RU)
- {
- $Window.Title = "Удалить дополнительные компоненты"
- $Button.Content = "Удалить"
- }
- else
- {
- $Window.Title = "Optional features (FODv2) to remove"
- $Button.Content = "Uninstall"
- }
-})
-
-# Button Click Event
-$Button.Add_Click({DeleteButton})
-#endregion Events Handlers
-
-if (Get-WindowsCapability -Online | Where-Object -FilterScript {($_.State -eq "Installed") -and ($_.Name -cnotmatch ($ExcludedCapabilities -join "|"))})
-{
- if ($RU)
- {
- Write-Verbose -Message "Диалоговое окно открывается..." -Verbose
- }
- else
- {
- Write-Verbose -Message "Displaying the dialog box..." -Verbose
- }
- # Display the dialog box
- # Отобразить диалоговое окно
- $Form.ShowDialog() | Out-Null
-}
-else
-{
- if ($RU)
- {
- Write-Verbose -Message "Отсутствуют данные" -Verbose
- }
- else
- {
- Write-Verbose -Message "Nothing to display" -Verbose
- }
-}
+WindowsManageDefaultPrinter -Disable
+
+# Let Windows decide which printer should be the default one (current user only) (default value)
+# Разрешать Windows решать, какой принтер должен использоваться по умолчанию (только для текущего пользователя) (значение по умолчанию)
+# WindowsManageDefaultPrinter -Enable
+
+# Disable the Windows features using the pop-up dialog box that enables the user to select features to remove
+# Отключить компоненты Windows, используя всплывающее диалоговое окно, позволяющее пользователю отметить компоненты на удаление
+WindowsFeatures -Disable
+
+# Enable the Windows features using the pop-up dialog box that enables the user to select features to remove
+# Включить компоненты Windows, используя всплывающее диалоговое окно, позволяющее пользователю отметить компоненты на удаление
+# WindowsFeatures -Enable
+
+# Disable Features On Demand v2 (FODv2) capabilities using the pop-up dialog box
+# Отключить компоненты "Функции по требованию" (FODv2), используя всплывающее диалоговое окно
+WindowsCapabilities -Disable
+
+# Enable Feature On Demand v2 (FODv2) capabilities using the pop-up dialog box
+# Включить компоненты "Функции по требованию" (FODv2), используя всплывающее диалоговое окно
+# WindowsCapabilities -Enable
# Opt-in to Microsoft Update service, so to receive updates for other Microsoft products
# Подключаться к службе Microsoft Update так, чтобы при обновлении Windows получать обновления для других продуктов Майкрософт
-(New-Object -ComObject Microsoft.Update.ServiceManager).AddService2("7971f918-a847-4430-9279-4a52d1efe18d", 7, "")
-
-# Open "Background apps" page
-# Открыть раздел "Фоновые приложения"
-Start-Process -FilePath ms-settings:privacy-backgroundapps
-
-# Set the power management scheme based on a device category
-# Установить схему управления питанием в зависимости от категории устройства
-if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -eq 2)
-{
- # Balanced for laptop
- # Сбалансированная для ноутбука
- POWERCFG /SETACTIVE SCHEME_BALANCED
-}
-else
-{
- # High performance for desktop
- # Высокая производительность для стационарного ПК
- POWERCFG /SETACTIVE SCHEME_MIN
-}
+UpdateMicrosoftProducts -Enable
+
+# Opt-out of Microsoft Update service, so not to receive updates for other Microsoft products (default value)
+# Не подключаться к службе Microsoft Update так, чтобы при обновлении Windows не получать обновления для других продуктов Майкрософт (значение по умолчанию)
+# UpdateMicrosoftProducts -Disable
+
+# Set the power management scheme on "High performance" if device is a desktop
+# Установить схему управления питанием на "Высокая производительность", если устройство является стационарным ПК
+PowerManagementScheme -High
+
+# Set the power management scheme on "Balanced" (default value)
+# Установить схему управления питанием на "Сбалансированная" (значение по умолчанию)
+# PowerManagementScheme -Balanced
# Use latest installed .NET runtime for all apps
# Использовать последнюю установленную среду выполнения .NET для всех приложений
-New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\.NETFramework -Name OnlyUseLatestCLR -PropertyType DWord -Value 1 -Force
-New-ItemProperty -Path HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework -Name OnlyUseLatestCLR -PropertyType DWord -Value 1 -Force
+LatestInstalled.NET -Enable
+
+# Do not use latest installed .NET runtime for all apps (default value)
+# Не использовать последнюю установленную версию .NET для всех приложений (значение по умолчанию)
+# LatestInstalled.NET -Disable
-# Do not allow the computer (if device is not a laptop) to turn off all the network adapters to save power
+# Do not allow the computer (if device is not a laptop) to turn off the network adapters to save power
# Запретить отключение всех сетевых адаптеров для экономии энергии (если устройство не является ноутбуком)
-if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2)
-{
- $Adapters = Get-NetAdapter -Physical | Get-NetAdapterPowerManagement | Where-Object -FilterScript {$_.AllowComputerToTurnOffDevice -ne "Unsupported"}
- foreach ($Adapter in $Adapters)
- {
- $Adapter.AllowComputerToTurnOffDevice = "Disabled"
- $Adapter | Set-NetAdapterPowerManagement
- }
-}
+PCTurnOffDevice -Disable
+
+# Allow the computer to turn off the network adapters to save power (default value)
+# Разрешить отключение всех сетевых адаптеров для экономии энергии (значение по умолчанию)
+# PCTurnOffDevice -Enable
# Set the default input method to the English language
# Установить метод ввода по умолчанию на английский язык
-Set-WinDefaultInputMethodOverride -InputTip "0409:00000409"
+SetInputMethod -English
+
+# Reset the default input method
+# Сбросить метод ввода по умолчанию
+# SetInputMethod -Default
-# Enable Windows Sandbox
-# Включить Windows Sandbox
-# Checking whether x86 virtualization is enabled in the firmware
-# Проверка: включена ли в настройках UEFI аппаратная виртуализация x86
-if ((Get-CimInstance -ClassName CIM_Processor).VirtualizationFirmwareEnabled -eq $true)
-{
- Enable-WindowsOptionalFeature -FeatureName Containers-DisposableClientVM -All -Online -NoRestart
-}
-else
-{
- try
- {
- # Determining whether Hyper-V is enabled
- # Проверка: включен ли Hyper-V
- if ((Get-CimInstance -ClassName CIM_ComputerSystem).HypervisorPresent -eq $true)
- {
- Enable-WindowsOptionalFeature -FeatureName Containers-DisposableClientVM -All -Online -NoRestart
- }
- }
- catch [Exception]
- {
- if ($RU)
- {
- Write-Error -Message "Включите в BIOS виртуализацию" -ErrorAction SilentlyContinue
- }
- else
- {
- Write-Error -Message "Enable Virtualization in BIOS" -ErrorAction SilentlyContinue
- }
- }
-}
-
-# Change the location of the user folders to %SystemDrive% (current user only)
-# Изменить расположение пользовательских папок на %SystemDrive% (только для текущего пользователя)
-function UserShellFolder
-{
<#
-.SYNOPSIS
- Change the location of the each user folders using SHSetKnownFolderPath function
-.EXAMPLE
- UserShellFolder -UserFolder Desktop -FolderPath "$env:SystemDrive:\Desktop" -RemoveDesktopINI
-.NOTES
- User files or folders won't me moved to the new location
- The RemoveDesktopINI argument removes desktop.ini in the old user shell folder
+ Change the location of the user folders to any disks root of your choice using the interactive menu (current user only)
+ User files or folders won't me moved to a new location
+
+ Изменить расположение пользовательских папок в корень любого диска на выбор с помощью интерактивного меню (только для текущего пользователя)
+ Пользовательские файлы и папки не будут перемещены в новое расположение
#>
- [CmdletBinding()]
- param
- (
- [Parameter(Mandatory = $true)]
- [ValidateSet("Desktop", "Documents", "Downloads", "Music", "Pictures", "Videos")]
- [string]
- $UserFolder,
-
- [Parameter(Mandatory = $true)]
- [string]
- $FolderPath,
-
- [Parameter(Mandatory = $false)]
- [switch]
- $RemoveDesktopINI
- )
-
- function KnownFolderPath
- {
- <#
- .SYNOPSIS
- Redirect user folders to a new location
- .EXAMPLE
- KnownFolderPath -KnownFolder Desktop -Path "$env:SystemDrive:\Desktop"
- .NOTES
- User files or folders won't me moved to the new location
- #>
- [CmdletBinding()]
- param
- (
- [Parameter(Mandatory = $true)]
- [ValidateSet("Desktop", "Documents", "Downloads", "Music", "Pictures", "Videos")]
- [string]
- $KnownFolder,
-
- [Parameter(Mandatory = $true)]
- [string]
- $Path
- )
-
- $KnownFolders = @{
- "Desktop" = @("B4BFCC3A-DB2C-424C-B029-7FE99A87C641");
- "Documents" = @("FDD39AD0-238F-46AF-ADB4-6C85480369C7", "f42ee2d3-909f-4907-8871-4c22fc0bf756");
- "Downloads" = @("374DE290-123F-4565-9164-39C4925E467B", "7d83ee9b-2244-4e70-b1f5-5393042af1e4");
- "Music" = @("4BD8D571-6D19-48D3-BE97-422220080E43", "a0c69a99-21c8-4671-8703-7934162fcf1d");
- "Pictures" = @("33E28130-4E1E-4676-835A-98395C3BC3BB", "0ddd015d-b06c-45d5-8c4c-f59713854639");
- "Videos" = @("18989B1D-99B5-455B-841C-AB7C74E4DDFC", "35286a68-3c57-41a1-bbb1-0eae73d76c95");
- }
-
- $Signature = @{
- Namespace = "WinAPI"
- Name = "KnownFolders"
- Language = "CSharp"
- MemberDefinition = @"
-[DllImport("shell32.dll")]
-public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, IntPtr token, [MarshalAs(UnmanagedType.LPWStr)] string path);
-"@
- }
- if (-not ("WinAPI.KnownFolders" -as [type]))
- {
- Add-Type @Signature
- }
-
- foreach ($guid in $KnownFolders[$KnownFolder])
- {
- [WinAPI.KnownFolders]::SHSetKnownFolderPath([ref]$guid, 0, 0, $Path)
- }
- (Get-Item -Path $Path -Force).Attributes = "ReadOnly"
- }
-
- $UserShellFoldersRegName = @{
- "Desktop" = "Desktop"
- "Documents" = "Personal"
- "Downloads" = "{374DE290-123F-4565-9164-39C4925E467B}"
- "Music" = "My Music"
- "Pictures" = "My Pictures"
- "Videos" = "My Video"
- }
-
- $UserShellFoldersGUID = @{
- "Desktop" = "{754AC886-DF64-4CBA-86B5-F7FBF4FBCEF5}"
- "Documents" = "{F42EE2D3-909F-4907-8871-4C22FC0BF756}"
- "Downloads" = "{7D83EE9B-2244-4E70-B1F5-5393042AF1E4}"
- "Music" = "{A0C69A99-21C8-4671-8703-7934162FCF1D}"
- "Pictures" = "{0DDD015D-B06C-45D5-8C4C-F59713854639}"
- "Videos" = "{35286A68-3C57-41A1-BBB1-0EAE73D76C95}"
- }
-
- # Contents of the hidden desktop.ini file for each type of user folders
- # Содержимое скрытого файла desktop.ini для каждого типа пользовательских папок
- $DesktopINI = @{
- "Desktop" = "",
- "[.ShellClassInfo]",
- "LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21769",
- "IconResource=%SystemRoot%\system32\imageres.dll,-183"
- "Documents" = "",
- "[.ShellClassInfo]",
- "LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21770",
- "IconResource=%SystemRoot%\system32\imageres.dll,-112",
- "IconFile=%SystemRoot%\system32\shell32.dll",
- "IconIndex=-235"
- "Downloads" = "",
- "[.ShellClassInfo]","LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21798",
- "IconResource=%SystemRoot%\system32\imageres.dll,-184"
- "Music" = "",
- "[.ShellClassInfo]","LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21790",
- "InfoTip=@%SystemRoot%\system32\shell32.dll,-12689",
- "IconResource=%SystemRoot%\system32\imageres.dll,-108",
- "IconFile=%SystemRoot%\system32\shell32.dll","IconIndex=-237"
- "Pictures" = "",
- "[.ShellClassInfo]",
- "LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21779",
- "InfoTip=@%SystemRoot%\system32\shell32.dll,-12688",
- "IconResource=%SystemRoot%\system32\imageres.dll,-113",
- "IconFile=%SystemRoot%\system32\shell32.dll",
- "IconIndex=-236"
- "Videos" = "",
- "[.ShellClassInfo]",
- "LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21791",
- "InfoTip=@%SystemRoot%\system32\shell32.dll,-12690",
- "IconResource=%SystemRoot%\system32\imageres.dll,-189",
- "IconFile=%SystemRoot%\system32\shell32.dll","IconIndex=-238"
- }
-
- # Determining the current user folder path
- # Определяем текущее значение пути пользовательской папки
- $UserShellFolderRegValue = Get-ItemPropertyValue -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name $UserShellFoldersRegName[$UserFolder]
- if ($UserShellFolderRegValue -ne $FolderPath)
- {
- if ((Get-ChildItem -Path $UserShellFolderRegValue | Measure-Object).Count -ne 0)
- {
- if ($RU)
- {
- Write-Error -Message "В папке $UserShellFolderRegValue осталась файлы. Переместите их вручную в новое расположение" -ErrorAction SilentlyContinue
- }
- else
- {
- Write-Error -Message "Some files left in the $UserShellFolderRegValue folder. Move them manually to a new location" -ErrorAction SilentlyContinue
- }
- }
-
- # Creating a new folder if there is no one
- # Создаем новую папку, если таковая отсутствует
- if (-not (Test-Path -Path $FolderPath))
- {
- New-Item -Path $FolderPath -ItemType Directory -Force
- }
-
- # Removing old desktop.ini
- # Удаляем старый desktop.ini
- if ($RemoveDesktopINI.IsPresent)
- {
- Remove-Item -Path "$UserShellFolderRegValue\desktop.ini" -Force
- }
-
- KnownFolderPath -KnownFolder $UserFolder -Path $FolderPath
- New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name $UserShellFoldersGUID[$UserFolder] -PropertyType ExpandString -Value $FolderPath -Force
-
- Set-Content -Path "$FolderPath\desktop.ini" -Value $DesktopINI[$UserFolder] -Encoding Unicode -Force
- (Get-Item -Path "$FolderPath\desktop.ini" -Force).Attributes = "Hidden", "System", "Archive"
- (Get-Item -Path "$FolderPath\desktop.ini" -Force).Refresh()
- }
-}
+SetUserShellFolderLocation -Root
<#
-.SYNOPSIS
- The "Show menu" function using PowerShell with the up/down arrow keys and enter key to make a selection
-.EXAMPLE
- ShowMenu -Menu $ListOfItems -Default $DefaultChoice
-.NOTES
- Doesn't work in PowerShell ISE
+ Select a folder for the location of the user folders manually using a folder browser dialog (current user only)
+ User files or folders won't me moved to a new location
+
+ Выбрать папку для расположения пользовательских папок вручную, используя диалог "Обзор папок" (только для текущего пользователя)
+ Пользовательские файлы и папки не будут перемещены в новое расположение
#>
-function ShowMenu
-{
- [CmdletBinding()]
- param
- (
- [Parameter()]
- [string]
- $Title,
-
- [Parameter(Mandatory = $true)]
- [array]
- $Menu,
-
- [Parameter(Mandatory = $true)]
- [int]
- $Default
- )
-
- Write-Information -MessageData $Title -InformationAction Continue
-
- $minY = [Console]::CursorTop
- $y = [Math]::Max([Math]::Min($Default, $Menu.Count), 0)
- do
- {
- [Console]::CursorTop = $minY
- [Console]::CursorLeft = 0
- $i = 0
- foreach ($item in $Menu)
- {
- if ($i -ne $y)
- {
- Write-Information -MessageData (' {0}. {1} ' -f ($i+1), $item) -InformationAction Continue
- }
- else
- {
- Write-Information -MessageData ('[ {0}. {1} ]' -f ($i+1), $item) -InformationAction Continue
- }
- $i++
- }
-
- $k = [Console]::ReadKey()
- switch ($k.Key)
- {
- "UpArrow"
- {
- if ($y -gt 0)
- {
- $y--
- }
- }
- "DownArrow"
- {
- if ($y -lt ($Menu.Count - 1))
- {
- $y++
- }
- }
- "Enter"
- {
- return $Menu[$y]
- }
- }
- }
- while ($k.Key -notin ([ConsoleKey]::Escape, [ConsoleKey]::Enter))
-}
-
-# Store all drives letters to use them within ShowMenu function
-# Сохранить все буквы диска, чтобы использовать их в функции ShowMenu
-if ($RU)
-{
- Write-Verbose "Получение дисков..." -Verbose
-}
-else
-{
- Write-Verbose "Retrieving drives..." -Verbose
-}
-$DriveLetters = @((Get-Disk | Where-Object -FilterScript {$_.BusType -ne "USB"} | Get-Partition | Get-Volume | Where-Object -FilterScript {$null -ne $_.DriveLetter}).DriveLetter | Sort-Object)
-
-# If the number of disks is more than one, set the second drive in the list as default drive
-# Если количество дисков больше одного, сделать второй диск в списке диском по умолчанию
-if ($DriveLetters.Count -gt 1)
-{
- $Default = 1
-}
-else
-{
- $Default = 0
-}
-
-# Desktop
-# Рабочий стол
-$Title = ""
-if ($RU)
-{
- $Message = "Изменить местоположение папки `"Рабочий стол`"?"
- Write-Warning -Message "`nФайлы не будут перенесены"
- $Options = "&Изменить", "&Пропустить"
-}
-else
-{
- $Message = "Would you like to change the location of the Desktop folder?"
- Write-Warning -Message "`nFiles will not be moved"
- $Options = "&Change", "&Skip"
-}
-$DefaultChoice = 1
-$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
-
-switch ($Result)
-{
- "0"
- {
- if ($RU)
- {
- $Title = "`nВыберите диск, в корне которого будет создана папка для `"Рабочий стол`""
- }
- else
- {
- $Title = "`nSelect the drive within the root of which the `"Desktop`" folder will be created"
- }
- $SelectedDrive = ShowMenu -Title $Title -Menu $DriveLetters -Default $Default
- UserShellFolder -UserFolder Desktop -FolderPath "${SelectedDrive}:\Desktop" -RemoveDesktopINI
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
-}
-
-# Documents
-# Документы
-$Title = ""
-if ($RU)
-{
- $Message = "Чтобы изменить местоположение папки `"Документы`", введите необходимую букву"
- Write-Warning -Message "`nФайлы не будут перенесены"
- $Options = "&Изменить", "&Пропустить"
-}
-else
-{
- $Message = "To change the location of the Documents folder enter the required letter"
- Write-Warning -Message "`nFiles will not be moved"
- $Options = "&Change", "&Skip"
-}
-$DefaultChoice = 1
-$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
-
-switch ($Result)
-{
- "0"
- {
- if ($RU)
- {
- $Title = "`nВыберите диск, в корне которого будет создана папка для `"Документы`""
- }
- else
- {
- $Title = "`nSelect the drive within the root of which the `"Documents`" folder will be created"
- }
- $SelectedDrive = ShowMenu -Title $Title -Menu $DriveLetters -Default $Default
- UserShellFolder -UserFolder Documents -FolderPath "${SelectedDrive}:\Documents" -RemoveDesktopINI
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
-}
-
-# Downloads
-# Загрузки
-$Title = ""
-if ($RU)
-{
- $Message = "Изменить местоположение папки `"Загрузки`"?"
- Write-Warning -Message "`nФайлы не будут перенесены"
- $Options = "&Изменить", "&Пропустить"
-}
-else
-{
- $Message = "Would you like to change the location of the Downloads folder?"
- Write-Warning -Message "`nFiles will not be moved"
- $Options = "&Change", "&Skip"
-}
-$DefaultChoice = 1
-$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
-
-switch ($Result)
-{
- "0"
- {
- if ($RU)
- {
- $Title = "`nВыберите диск, в корне которого будет создана папка для `"Загрузки`""
- }
- else
- {
- $Title = "`nSelect the drive within the root of which the `"Downloads`" folder will be created"
- }
- $SelectedDrive = ShowMenu -Title $Title -Menu $DriveLetters -Default $Default
- UserShellFolder -UserFolder Downloads -FolderPath "${SelectedDrive}:\Downloads" -RemoveDesktopINI
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
-}
-
-# Music
-# Музыка
-$Title = ""
-if ($RU)
-{
- $Message = "Изменить местоположение папки `"Музыка`"?"
- Write-Warning -Message "`nФайлы не будут перенесены"
- $Options = "&Изменить", "&Пропустить"
-}
-else
-{
- $Message = "Would you like to change the location of the Music folder?"
- Write-Warning -Message "`nFiles will not be moved"
- $Options = "&Change", "&Skip"
-}
-$DefaultChoice = 1
-$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
-
-switch ($Result)
-{
- "0"
- {
- if ($RU)
- {
- $Title = "`nВыберите диск, в корне которого будет создана папка для `"Музыка`""
- }
- else
- {
- $Title = "`nSelect the drive within the root of which the `"Music`" folder will be created"
- }
- $SelectedDrive = ShowMenu -Title $Title -Menu $DriveLetters -Default $Default
- UserShellFolder -UserFolder Music -FolderPath "${SelectedDrive}:\Music" -RemoveDesktopINI
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
-}
-
-
-# Pictures
-# Изображения
-$Title = ""
-if ($RU)
-{
- $Message = "Чтобы изменить местоположение папки `"Изображения`", введите необходимую букву"
- Write-Warning -Message "`nФайлы не будут перенесены"
- $Options = "&Изменить", "&Пропустить"
-}
-else
-{
- $Message = "To change the location of the Pictures folder enter the required letter"
- Write-Warning -Message "`nFiles will not be moved"
- $Options = "&Change", "&Skip"
-}
-$DefaultChoice = 1
-$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
-
-switch ($Result)
-{
- "0"
- {
- if ($RU)
- {
- $Title = "`nВыберите диск, в корне которого будет создана папка для `"Изображения`""
- }
- else
- {
- $Title = "`nSelect the drive within the root of which the `"Pictures`" folder will be created"
- }
- $SelectedDrive = ShowMenu -Title $Title -Menu $DriveLetters -Default $Default
- UserShellFolder -UserFolder Pictures -FolderPath "${SelectedDrive}:\Pictures" -RemoveDesktopINI
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
-}
-
-# Videos
-# Видео
-$Title = ""
-if ($RU)
-{
- $Message = "Изменить местоположение папки `"Видео`"?"
- Write-Warning -Message "`nФайлы не будут перенесены"
- $Options = "&Изменить", "&Пропустить"
-}
-else
-{
- $Message = "Would you like to change the location of the Videos folder?"
- Write-Warning -Message "`nFiles will not be moved"
- $Options = "&Change", "&Skip"
-}
-$DefaultChoice = 1
-$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
-
-switch ($Result)
-{
- "0"
- {
- if ($RU)
- {
- $Title = "`nВыберите диск, в корне которого будет создана папка для `"Видео`""
- }
- else
- {
- $Title = "`nSelect the drive within the root of which the `"Videos`" folder will be created"
- }
- $SelectedDrive = ShowMenu -Title $Title -Menu $DriveLetters -Default $Default
- UserShellFolder -UserFolder Videos -FolderPath "${SelectedDrive}:\Videos" -RemoveDesktopINI
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
-}
+# SetUserShellFolderLocation -Custom
+
+<#
+ Change the location of the user folders to the default values (current user only)
+ User files or folders won't me moved to the new location
+
+ Изменить расположение пользовательских папок на значения по умолчанию (только для текущего пользователя)
+ Пользовательские файлы и папки не будут перемещены в новое расположение
+#>
+# SetUserShellFolderLocation -Default
# Save screenshots by pressing Win+PrtScr to the Desktop folder (current user only)
# Сохранять скриншоты по нажатию Win+PrtScr в папку "рабочий стол" (только для текущего пользователя)
-$DesktopFolder = Get-ItemPropertyValue -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name Desktop
-Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name "{B7BEDE81-DF94-4682-A7D8-57A52620B86F}" -Type ExpandString -Value $DesktopFolder -Force
-
-# Save all opened folders in order to restore them after File Explorer restart
-# Сохранить все открытые папки, чтобы восстановить их после перезапуска проводника
-Clear-Variable -Name OpenedFolders -Force -ErrorAction Ignore
-$OpenedFolders = {(New-Object -ComObject Shell.Application).Windows() | ForEach-Object -Process {$_.Document.Folder.Self.Path}}.Invoke()
-
-# In order for the changes to take effect the File Explorer process has to be restarted
-# Чтобы изменения вступили в силу, необходимо перезапустить процесс проводника
-Stop-Process -Name explorer -Force
-
-# Restore closed folders
-# Восстановить закрытые папки
-foreach ($OpenedFolder in $OpenedFolders)
-{
- if (Test-Path -Path $OpenedFolder)
- {
- Invoke-Item -Path $OpenedFolder
- }
-}
+WinPrtScrFolder -Desktop
+
+# Save screenshots by pressing Win+PrtScr to the Pictures folder (current user only) (default value)
+# Cохранять скриншоты по нажатию Win+PrtScr в папку "Изображения" (только для текущего пользователя) (значение по умолчанию)
+# WinPrtScrFolder -Default
# Launch folder windows in a separate process (current user only)
# Запускать окна с папками в отдельном процессе (только для текущего пользователя)
-New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SeparateProcess -PropertyType DWord -Value 1 -Force
+FoldersLaunchSeparateProcess -Enable
+# Do not launch folder windows in a separate process (current user only) (default value)
+# Не запускать окна с папками в отдельном процессе (только для текущего пользователя) (значение по умолчанию)
+# FoldersLaunchSeparateProcess -Disable
# Disable help lookup via F1 (current user only)
# Отключить открытие справки по нажатию F1 (только для текущего пользователя)
-if (-not (Test-Path -Path "HKCU:\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win64"))
-{
- New-Item -Path "HKCU:\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win64" -Force
-}
-New-ItemProperty -Path "HKCU:\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win64" -Name "(Default)" -PropertyType String -Value "" -Force
+F1HelpPage -Disable
-# Turn on Num Lock at startup
+# Enable help lookup via F1 (current user only) (default value)
+# Включить открытие справки по нажатию F1 (только для текущего пользователя) (значение по умолчанию)
+# F1HelpPage -Enable
+
+# Enable Num Lock at startup
# Включить Num Lock при загрузке
-New-ItemProperty -Path "Registry::HKEY_USERS\.DEFAULT\Control Panel\Keyboard" -Name InitialKeyboardIndicators -PropertyType String -Value 2147483650 -Force
+NumLock -Enable
+
+# Disable Num Lock at startup (default value)
+# Выключить Num Lock при загрузке (значение по умолчанию)
+# NumLock -Disable
-# Do not activate StickyKey after tapping the Shift key 5 times (current user only)
-# Не включать залипание клавиши Shift после 5 нажатий (только для текущего пользователя)
-New-ItemProperty -Path "HKCU:\Control Panel\Accessibility\StickyKeys" -Name Flags -PropertyType String -Value 506 -Force
+# Disable StickyKey after tapping the Shift key 5 times (current user only)
+# Выключить залипание клавиши Shift после 5 нажатий (только для текущего пользователя)
+StickyShift -Disable
-# Do not use AutoPlay for all media and devices (current user only)
-# Не использовать автозапуск для всех носителей и устройств (только для текущего пользователя)
-New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -PropertyType DWord -Value 1 -Force
+# Enable StickyKey after tapping the Shift key 5 times (current user only) (default value)
+# Включить залипание клавиши Shift после 5 нажатий (только для текущего пользователя) (значение по умолчанию)
+# StickyShift -Enable
+
+# Disable AutoPlay for all media and devices (current user only)
+# Выключать автозапуск для всех носителей и устройств (только для текущего пользователя)
+Autoplay -Disable
+
+# Enable AutoPlay for all media and devices (current user only) (default value)
+# Включить автозапуск для всех носителей и устройств (только для текущего пользователя) (значение по умолчанию)
+# Autoplay -Enable
# Disable thumbnail cache removal
# Отключить удаление кэша миниатюр
-New-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Thumbnail Cache" -Name Autorun -PropertyType DWord -Value 0 -Force
+ThumbnailCacheRemoval -Disable
+
+# Enable thumbnail cache removal (default value)
+# Включить удаление кэша миниатюр (значение по умолчанию)
+# ThumbnailCacheRemoval -Enable
# Enable "Network Discovery" and "File and Printers Sharing" for workgroup networks
# Включить сетевое обнаружение и общий доступ к файлам и принтерам для рабочих групп
-if ((Get-CimInstance -ClassName CIM_ComputerSystem).PartOfDomain -eq $false)
-{
- $FirewallRules = @(
- # File and printer sharing
- # Общий доступ к файлам и принтерам
- "@FirewallAPI.dll,-32752",
-
- # Network discovery
- # Сетевое обнаружение
- "@FirewallAPI.dll,-28502"
- )
- Set-NetFirewallRule -Group $FirewallRules -Profile Private -Enabled True
-}
+NetworkDiscovery -Enable
+
+# Disable "Network Discovery" and "File and Printers Sharing" for workgroup networks (default value)
+# Выключить сетевое обнаружение и общий доступ к файлам и принтерам для рабочих групп (значение по умолчанию)
+# NetworkDiscovery -Disable
# Automatically adjust active hours for me based on daily usage
# Автоматически изменять период активности для этого устройства на основе действий
-New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name SmartActiveHoursState -PropertyType DWord -Value 1 -Force
+SmartActiveHours -Enable
+
+# Do not automatically adjust active hours for me based on daily usage (default value)
+# Не изменять автоматически период активности для этого устройства на основе действий (значение по умолчанию)
+# SmartActiveHours -Disable
#endregion System
#region Start menu
-# Do not show recently added apps in the Start menu
-# Не показывать недавно добавленные приложения в меню "Пуск"
-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 HideRecentlyAddedApps -PropertyType DWord -Value 1 -Force
-
-# Do not show app suggestions in the Start menu
-# Не показывать рекомендации в меню "Пуск"
-New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338388Enabled -PropertyType DWord -Value 0 -Force
+# Hide recently added apps in the Start menu
+# Скрывать недавно добавленные приложения в меню "Пуск"
+RecentlyAddedApps -Hide
+
+# Show recently added apps in the Start menu (default value)
+# Показывать недавно добавленные приложения в меню "Пуск" (значение по умолчанию)
+# RecentlyAddedApps -Show
+
+# Hide app suggestions in the Start menu
+# Скрывать рекомендации в меню "Пуск"
+AppSuggestions -Hide
+
+# Show app suggestions in the Start menu (default value)
+# Показывать рекомендации в меню "Пуск" (значение по умолчанию)
+# AppSuggestions -Show
# Run the Command Prompt shortcut from the Start menu as Administrator
# Запускать ярлык командной строки в меню "Пуск" от имени Администратора
-[byte[]]$bytes = Get-Content -Path "$env:APPDATA\Microsoft\Windows\Start menu\Programs\System Tools\Command Prompt.lnk" -Encoding Byte -Raw
-$bytes[0x15] = $bytes[0x15] -bor 0x20
-Set-Content -Path "$env:APPDATA\Microsoft\Windows\Start menu\Programs\System Tools\Command Prompt.lnk" -Value $bytes -Encoding Byte -Force
+RunCMDShortcut -Elevated
+# Run the Command Prompt shortcut from the Start menu as user (default value)
+# Запускать ярлык командной строки в меню "Пуск" от имени пользователя (значение по умолчанию)
+# RunCMDShortcut -NonElevated
#endregion Start menu
#region Gaming
-# Turn off Xbox Game Bar
+# Disable Xbox Game Bar
# Отключить Xbox Game Bar
-New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\GameDVR -Name AppCaptureEnabled -PropertyType DWord -Value 0 -Force
-New-ItemProperty -Path HKCU:\System\GameConfigStore -Name GameDVR_Enabled -PropertyType DWord -Value 0 -Force
+XboxGameBar -Disable
+
+# Enable Xbox Game Bar (default value)
+# Включить Xbox Game Bar (значение по умолчанию)
+# XboxGameBar -Enable
-# Turn off Xbox Game Bar tips
+# Disable Xbox Game Bar tips
# Отключить советы Xbox Game Bar
-New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\GameBar -Name ShowStartupPanel -PropertyType DWord -Value 0 -Force
-
-# Set "High performance" in graphics performance preference for apps
-# Установить параметры производительности графики для отдельных приложений на "Высокая производительность"
-if (Get-CimInstance -ClassName Win32_VideoController | Where-Object -FilterScript {$_.AdapterDACType -ne "Internal" -and $null -ne $_.AdapterDACType})
-{
- if ($RU)
- {
- $Title = "Настройка производительности графики"
- $Message = "Установить для любого приложения по вашему выбору настройки производительности графики на `"Высокая производительность`"?"
- $Options = "&Создать", "&Пропустить"
- }
- else
- {
- $Title = "Graphics performance preference"
- $Message = "Would you like to set the graphics performance setting of an app of your choice to `"High performance`"?"
- $Options = "&Add", "&Skip"
- }
- $DefaultChoice = 1
-
- do
- {
- $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
- switch ($Result)
- {
- "0"
- {
- Add-Type -AssemblyName System.Windows.Forms
- $OpenFileDialog = New-Object -TypeName System.Windows.Forms.OpenFileDialog
- if ($RU)
- {
- $OpenFileDialog.Filter = "*.exe|*.exe|Все файлы (*.*)|*.*"
- }
- else
- {
- $OpenFileDialog.Filter = "*.exe|*.exe|All Files (*.*)|*.*"
- }
- $OpenFileDialog.InitialDirectory = "${env:ProgramFiles(x86)}"
- $OpenFileDialog.Multiselect = $false
- # Focus on open file dialog
- # Перевести фокус на диалог открытия файла
- $tmp = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
- $OpenFileDialog.ShowDialog($tmp)
- if ($OpenFileDialog.FileName)
- {
- if (-not (Test-Path -Path HKCU:\SOFTWARE\Microsoft\DirectX\UserGpuPreferences))
- {
- New-Item -Path HKCU:\SOFTWARE\Microsoft\DirectX\UserGpuPreferences -Force
- }
- New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\DirectX\UserGpuPreferences -Name $OpenFileDialog.FileName -PropertyType String -Value "GpuPreference=2;" -Force
- }
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
- }
- }
- until ($Result -eq 1)
-}
+XboxGameTips -Disable
+
+# Enable Xbox Game Bar tips (default value)
+# Включить советы Xbox Game Bar (значение по умолчанию)
+# XboxGameTips -Enable
+
+<#
+ Set "High performance" in graphics performance preference for an app
+ Only with a dedicated GPU
+
+ Установить параметры производительности графики для отдельных приложений на "Высокая производительность"
+ Только при наличии внешней видеокарты
+#>
+SetAppGraphicsPerformance
#endregion Gaming
#region Scheduled tasks
<#
-Create a task to clean up unused files and Windows updates in the Task Scheduler
-The task runs every 90 days
+ Create the "Windows Cleanup" task to clean up unused files and Windows updates in the Task Scheduler
+ A minute before the task starts, a warning in the Windows action center will appear
+ The task runs every 90 days
-Создать задачу в Планировщике задач по очистке неиспользуемых файлов и обновлений Windows
-Задача выполняется каждые 90 дней
+ Создать задачу "Windows Cleanup" в Планировщике задач по очистке неиспользуемых файлов и обновлений Windows
+ За минуту до выполнения задачи в Центре уведомлений Windows появится предупреждение
+ Задача выполняется каждые 90 дней
#>
-Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches | ForEach-Object -Process {
- Remove-ItemProperty -Path $_.PsPath -Name StateFlags1337 -Force -ErrorAction Ignore
-}
-
-$VolumeCaches = @(
- # Delivery Optimization Files
- # Файлы оптимизации доставки
- "Delivery Optimization Files",
-
- # Device driver packages
- # Пакеты драйверов устройств
- "Device Driver Packages",
-
- # Previous Windows Installation(s)
- # Предыдущие установки Windows
- "Previous Installations",
-
- # Setup log files
- # Файлы журнала установки
- "Setup Log Files",
-
- # Temporary Setup Files
- # Временные файлы установки
- "Temporary Setup Files",
-
- # Microsoft Defender
- "Windows Defender",
-
- # Windows upgrade log files
- # Файлы журнала обновления Windows
- "Windows Upgrade Log Files"
-)
-foreach ($VolumeCache in $VolumeCaches)
-{
- New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\$VolumeCache" -Name StateFlags1337 -PropertyType DWord -Value 2 -Force
-}
-
-$PS1Script = '
-$app = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\cleanmgr.exe"
-
-[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
-$Template = [Windows.UI.Notifications.ToastTemplateType]::ToastImageAndText01
-[xml]$ToastTemplate = ([Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent($Template).GetXml())
-
-if ($PSUICulture -eq "ru-RU")
-{
- [xml]$ToastTemplate = @"
-
-
-
- Очистка неиспользуемых файлов и обновлений Windows начнется через минуту
-
-
-
-
-
-
-"@
-}
-else
-{
- [xml]$ToastTemplate = @"
-
-
-
- Cleaning up unused Windows files and updates starts in a minute
-
-
-
-
-
-
-"@
-}
-
-$ToastXml = New-Object -TypeName Windows.Data.Xml.Dom.XmlDocument
-$ToastXml.LoadXml($ToastTemplate.OuterXml)
-
-[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($app).Show($ToastXml)
-
-Start-Sleep -Seconds 60
-
-# Process startup info
-# Параметры запуска процесса
-$ProcessInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo
-$ProcessInfo.FileName = "$env:SystemRoot\system32\cleanmgr.exe"
-$ProcessInfo.Arguments = "/sagerun:1337"
-$ProcessInfo.UseShellExecute = $true
-$ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Minimized
-
-# Process object using the startup info
-# Объект процесса, используя заданные параметры
-$Process = New-Object System.Diagnostics.Process
-$Process.StartInfo = $ProcessInfo
-
-# Start the process
-# Запуск процесса
-$Process.Start() | Out-Null
-
-Start-Sleep -Seconds 3
-$SourceMainWindowHandle = (Get-Process -Name cleanmgr).MainWindowHandle
-
-function MinimizeWindow
-{
- [CmdletBinding()]
- param
- (
- [Parameter(Mandatory = $true)]
- $Process
- )
-
- $ShowWindowAsync = @{
- Namespace = "WinAPI"
- Name = "Win32ShowWindowAsync"
- Language = "CSharp"
- MemberDefinition = @"
-[DllImport("user32.dll")]
-public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
-"@
- }
- if (-not ("WinAPI.Win32ShowWindowAsync" -as [type]))
- {
- Add-Type @ShowWindowAsync
- }
-
- $MainWindowHandle = (Get-Process -Name $Process).MainWindowHandle
- [WinAPI.Win32ShowWindowAsync]::ShowWindowAsync($MainWindowHandle, 2)
-}
-
-while ($true)
-{
- $CurrentMainWindowHandle = (Get-Process -Name cleanmgr).MainWindowHandle
- if ([int]$SourceMainWindowHandle -ne [int]$CurrentMainWindowHandle)
- {
- MinimizeWindow -Process cleanmgr
- break
- }
- Start-Sleep -Milliseconds 5
-}
-
-$ProcessInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo
-# Cleaning up unused updates
-# Очистка неиспользованных обновлений
-$ProcessInfo.FileName = "$env:SystemRoot\system32\dism.exe"
-$ProcessInfo.Arguments = "/Online /English /Cleanup-Image /StartComponentCleanup /NoRestart"
-$ProcessInfo.UseShellExecute = $true
-$ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Minimized
-
-# Process object using the startup info
-# Объект процесса, используя заданные параметры
-$Process = New-Object System.Diagnostics.Process
-$Process.StartInfo = $ProcessInfo
-
-# Start the process
-# Запуск процесса
-$Process.Start() | Out-Null
-'
-$EncodedScript = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($PS1Script))
-
-$Action = New-ScheduledTaskAction -Execute powershell.exe -Argument "-WindowStyle Hidden -EncodedCommand $EncodedScript"
-$Trigger = New-ScheduledTaskTrigger -Daily -DaysInterval 90 -At 9am
-$Settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -StartWhenAvailable
-$Principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -RunLevel Highest
-if ($RU)
-{
- $Description =
- "Очистка неиспользуемых файлов и обновлений Windows, используя встроенную программу Очистка диска. Чтобы расшифровать закодированную строку используйте [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(`"строка`"))"
-}
-else
-{
- $Description =
- "Cleaning up unused Windows files and updates using built-in Disk cleanup app. To decode encoded command use [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(`"string`"))"
-}
-$Parameters = @{
- "TaskName" = "Windows Cleanup"
- "TaskPath" = "Setup Script"
- "Principal" = $Principal
- "Action" = $Action
- "Description" = $Description
- "Settings" = $Settings
- "Trigger" = $Trigger
-}
-Register-ScheduledTask @Parameters -Force
+CleanUpTask -Register
+
+# Delete the "Windows Cleanup" task to clean up unused files and Windows updates in the Task Scheduler
+# Удалить задачу "Windows Cleanup" в Планировщике задач по очистке неиспользуемых файлов и обновлений Windows
+# CleanUpTask -Delete
<#
-Create a task to clear the %SystemRoot%\SoftwareDistribution\Download folder in the Task Scheduler
-The task runs on Thursdays every 4 weeks
+ Create the "SoftwareDistribution" task to clear the %SystemRoot%\SoftwareDistribution\Download folder in the Task Scheduler
+ The task runs on Thursdays every 4 weeks
-Создать задачу в Планировщике задач по очистке папки %SystemRoot%\SoftwareDistribution\Download
-Задача выполняется по четвергам каждую 4 неделю
+ Создать задачу "SoftwareDistribution" в Планировщике задач по очистке папки %SystemRoot%\SoftwareDistribution\Download
+ Задача выполняется по четвергам каждую 4 неделю
#>
-$Argument = "
- (Get-Service -Name wuauserv).WaitForStatus('Stopped', '01:00:00')
- Get-ChildItem -Path $env:SystemRoot\SoftwareDistribution\Download -Recurse -Force | Remove-Item -Recurse -Force
-"
-$Action = New-ScheduledTaskAction -Execute powershell.exe -Argument $Argument
-$Trigger = New-JobTrigger -Weekly -WeeksInterval 4 -DaysOfWeek Thursday -At 9am
-$Settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -StartWhenAvailable
-$Principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -RunLevel Highest
-if ($RU)
-{
- $Description = "Очистка папки %SystemRoot%\SoftwareDistribution\Download"
-}
-else
-{
- $Description = "The %SystemRoot%\SoftwareDistribution\Download folder cleaning"
-}
-$Parameters = @{
- "TaskName" = "SoftwareDistribution"
- "TaskPath" = "Setup Script"
- "Principal" = $Principal
- "Action" = $Action
- "Description" = $Description
- "Settings" = $Settings
- "Trigger" = $Trigger
-}
-Register-ScheduledTask @Parameters -Force
+SoftwareDistributionTask -Register
+
+# Delete the "SoftwareDistribution" task to clear the %SystemRoot%\SoftwareDistribution\Download folder in the Task Scheduler
+# Удалить задачу "SoftwareDistributionp" в Планировщике задач по очистке папки %SystemRoot%\SoftwareDistribution\Download
+# SoftwareDistributionTask -Delete
<#
-Create a task to clear the %TEMP% folder in the Task Scheduler
-The task runs every 62 days
+ Create the "Temp" task to clear the %TEMP% folder in the Task Scheduler
+ The task runs every 62 days
-Создать задачу в Планировщике задач по очистке папки %TEMP%
-Задача выполняется каждые 62 дня
+ Создать задачу "Temp" в Планировщике задач по очистке папки %TEMP%
+ Задача выполняется каждые 62 дня
#>
-$Argument = "Get-ChildItem -Path $env:TEMP -Force -Recurse | Remove-Item -Force -Recurse"
-$Action = New-ScheduledTaskAction -Execute powershell.exe -Argument $Argument
-$Trigger = New-ScheduledTaskTrigger -Daily -DaysInterval 62 -At 9am
-$Settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -StartWhenAvailable
-$Principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -RunLevel Highest
-if ($RU)
-{
- $Description = "Очистка папки %TEMP%"
-}
-else
-{
- $Description = "The %TEMP% folder cleaning"
-}
-$Parameters = @{
- "TaskName" = "Temp"
- "TaskPath" = "Setup Script"
- "Principal" = $Principal
- "Action" = $Action
- "Description" = $Description
- "Settings" = $Settings
- "Trigger" = $Trigger
-}
-Register-ScheduledTask @Parameters -Force
+TempTask -Register
+
+# Delete a task to clear the %TEMP% folder in the Task Scheduler
+# Удалить задачу в Планировщике задач по очистке папки %TEMP%
+# TempTask -Delete
#endregion Scheduled tasks
-#region Windows Defender & Security
-# Turn on Controlled folder access and add protected folders
+#region Microsoft Defender & Security
+# Enable Controlled folder access and add protected folders
# Включить контролируемый доступ к папкам и добавить защищенные папки
-if ($RU)
-{
- $Title = "Контролируемый доступ к папкам"
- $Message = "Хотите, чтобы Защитник Windows ограничивал доступ к указанным вами папкам с конфиденциальной информацией?"
- $Options = "&Добавить", "&Пропустить"
-}
-else
-{
- $Title = "Controlled folder access"
- $Message = "Would you like Windows Defender to restrict access to sensitive folders that you specify?"
- $Options = "&Add", "&Skip"
-}
-$DefaultChoice = 1
-
-do
-{
- $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
- switch ($Result)
- {
- "0"
- {
- Add-Type -AssemblyName System.Windows.Forms
- $FolderBrowserDialog = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog
- if ($RU)
- {
- $FolderBrowserDialog.Description = "Выберите папку"
- }
- else
- {
- $FolderBrowserDialog.Description = "Select a folder"
- }
- $FolderBrowserDialog.RootFolder = "MyComputer"
- # Focus on open file dialog
- # Перевести фокус на диалог открытия файла
- $tmp = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
-
- $FolderBrowserDialog.ShowDialog($tmp)
- if ($FolderBrowserDialog.SelectedPath)
- {
- Set-MpPreference -EnableControlledFolderAccess Enabled
- Add-MpPreference -ControlledFolderAccessProtectedFolders $FolderBrowserDialog.SelectedPath -Force
- }
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
- }
-}
-until ($Result -eq 1)
+AddProtectedFolders
+
+# Remove all added protected folders
+# Удалить все добавленные защищенные папки
+# RemoveProtectedFolders
# Allow an app through Controlled folder access
# Разрешить работу приложения через контролируемый доступ к папкам
-if ($RU)
-{
- $Title = "Контролируемый доступ к папкам"
- $Message = "Указать приложение, которому разрешена работа через контролируемый доступ к папкам"
- $Options = "&Добавить", "&Пропустить"
-}
-else
-{
- $Title = "Controlled folder access"
- $Message = "Would you like to specify an app that is allowed through Controlled Folder access?"
- $Options = "&Add", "&Skip"
-}
-$DefaultChoice = 1
-
-do
-{
- $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
- switch ($Result)
- {
- "0"
- {
- Add-Type -AssemblyName System.Windows.Forms
- $OpenFileDialog = New-Object -TypeName System.Windows.Forms.OpenFileDialog
- if ($RU)
- {
- $OpenFileDialog.Filter = "*.exe|*.exe|Все файлы (*.*)|*.*"
- }
- else
- {
- $OpenFileDialog.Filter = "*.exe|*.exe|All Files (*.*)|*.*"
- }
- $OpenFileDialog.InitialDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
- $OpenFileDialog.Multiselect = $false
- # Focus on open file dialog
- # Перевести фокус на диалог открытия файла
- $tmp = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
-
- $OpenFileDialog.ShowDialog($tmp)
- if ($OpenFileDialog.FileName)
- {
- Add-MpPreference -ControlledFolderAccessAllowedApplications $OpenFileDialog.FileName -Force
- }
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
- }
-}
-until ($Result -eq 1)
-
-# Add a folder to the exclusion from Windows Defender scanning
-# Добавить папку в список исключений сканирования Windows Defender
-if ($RU)
-{
- $Title = "Windows Defender"
- $Message = "Указать папку, чтобы исключить ее из списка сканирования Microsoft Defender?"
- $Options = "&Исключить", "&Пропустить"
-}
-else
-{
- $Title = "Windows Defender"
- $Message = "Would you like to specify a folder to be excluded from Microsoft Defender malware scans?"
- $Options = "&Exclude", "&Skip"
-}
-$DefaultChoice = 1
-
-do
-{
- $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
- switch ($Result)
- {
- "0"
- {
- Add-Type -AssemblyName System.Windows.Forms
- $FolderBrowserDialog = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog
- if ($RU)
- {
- $FolderBrowserDialog.Description = "Выберите папку"
- }
- else
- {
- $FolderBrowserDialog.Description = "Select a folder"
- }
- $FolderBrowserDialog.RootFolder = "MyComputer"
- # Focus on open file dialog
- # Перевести фокус на диалог открытия файла
- $tmp = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
-
- $FolderBrowserDialog.ShowDialog($tmp)
- if ($FolderBrowserDialog.SelectedPath)
- {
- Add-MpPreference -ExclusionPath $FolderBrowserDialog.SelectedPath -Force
- }
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
- }
-}
-until ($Result -eq 1)
-
-# Add a file to the exclusion from Windows Defender scanning
-# Добавить файл в список исключений сканирования Windows Defender
-if ($RU)
-{
- $Title = "Windows Defender"
- $Message = "Указать файл, чтобы исключить его из списка сканирования Microsoft Defender?"
- $Options = "&Исключить", "&Пропустить"
-}
-else
-{
- $Title = "Windows Defender"
- $Message = "Would you like to specify a file to be excluded from Microsoft Defender malware scans?"
- $Options = "&Exclude", "&Skip"
-}
-$DefaultChoice = 1
-
-do
-{
- $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
- switch ($Result)
- {
- "0"
- {
- Add-Type -AssemblyName System.Windows.Forms
- $OpenFileDialog = New-Object -TypeName System.Windows.Forms.OpenFileDialog
- if ($RU)
- {
- $OpenFileDialog.Filter = "Все файлы (*.*)|*.*"
- }
- else
- {
- $OpenFileDialog.Filter = "All Files (*.*)|*.*"
- }
- $OpenFileDialog.InitialDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
- $OpenFileDialog.Multiselect = $false
- # Focus on open file dialog
- # Перевести фокус на диалог открытия файла
- $tmp = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
-
- $OpenFileDialog.ShowDialog($tmp)
- if ($OpenFileDialog.FileName)
- {
- Add-MpPreference -ExclusionPath $OpenFileDialog.FileName -Force
- }
- }
- "1"
- {
- if ($RU)
- {
- Write-Verbose -Message "Пропущено" -Verbose
- }
- else
- {
- Write-Verbose -Message "Skipped" -Verbose
- }
- }
- }
-}
-until ($Result -eq 1)
-
-# Turn on Windows Defender Exploit Guard network protection
-# Включить защиту сети в Windows Defender Exploit Guard
-Set-MpPreference -EnableNetworkProtection Enabled
-
-# Turn on detection for potentially unwanted applications and block them
+AddAppControlledFolder
+
+# Remove all allowed apps through Controlled folder access
+# Удалить все добавленные разрешенные приложение через контролируемый доступ к папкам
+# RemoveAllowedAppsControlledFolder
+
+# Add a folder to the exclusion from Microsoft Defender scanning
+# Добавить папку в список исключений сканирования Microsoft Defender
+AddDefenderExclusionFolder
+
+# Remove all excluded folders from Microsoft Defender scanning
+# Удалить все папки из списка исключений сканирования Microsoft Defender
+# RemoveDefenderExclusionFolders
+
+# Add a file to the exclusion from Microsoft Defender scanning
+# Добавить файл в список исключений сканирования Microsoft Defender
+AddDefenderExclusionFile
+
+# Remove all excluded files from Microsoft Defender scanning
+# Удалить все файлы из списка исключений сканирования Microsoft Defender
+# RemoveDefenderExclusionFiles
+
+# Enable Microsoft Defender Exploit Guard network protection
+# Включить защиту сети в Microsoft Defender Exploit Guard
+NetworkProtection -Enable
+
+# Disable Microsoft Defender Exploit Guard network protection (default value)
+# Выключить защиту сети в Microsoft Defender Exploit Guard
+# NetworkProtection -Disable
+
+# Enable detection for potentially unwanted applications and block them
# Включить обнаружение потенциально нежелательных приложений и блокировать их
-Set-MpPreference -PUAProtection Enabled
+PUAppsDetection -Enable
+
+# Disable detection for potentially unwanted applications and block them (default value)
+# Выключить обнаружение потенциально нежелательных приложений и блокировать их (значение по умолчанию)
+# PUAppsDetection -Disable
+
+# Enable sandboxing for Microsoft Defender
+# Включить песочницу для Microsoft Defender
+DefenderSandbox -Enable
-# Run Windows Defender within a sandbox
-# Запускать Защитника Windows в песочнице
-setx /M MP_FORCE_USE_SANDBOX 1
+# Disable sandboxing for Microsoft Defender (default value)
+# Выключить песочницу для Microsoft Defender (значение по умолчанию)
+# DefenderSandbox -Disable
-# Dismiss Windows Defender offer in the Windows Security about signing in Microsoft account
-# Отклонить предложение Защитника Windows в "Безопасность Windows" о входе в аккаунт Microsoft
-New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows Security Health\State" -Name AccountProtection_MicrosoftAccount_Disconnected -PropertyType DWord -Value 1 -Force
+# Dismiss Microsoft Defender offer in the Windows Security about signing in Microsoft account
+# Отклонить предложение Microsoft Defender в "Безопасность Windows" о входе в аккаунт Microsoft
+DismissMSAccount
-# Dismiss Windows Defender offer in the Windows Security about turning on the SmartScreen filter for Microsoft Edge
-# Отклонить предложение Защитника Windows в "Безопасность Windows" включить фильтр SmartScreen для Microsoft Edge
-New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows Security Health\State" -Name AppAndBrowser_EdgeSmartScreenOff -PropertyType DWord -Value 0 -Force
+# Dismiss Microsoft Defender offer in the Windows Security about turning on the SmartScreen filter for Microsoft Edge
+# Отклонить предложение Microsoft Defender в "Безопасность Windows" включить фильтр SmartScreen для Microsoft Edge
+DismissSmartScreenFilter
-# Turn on events auditing generated when a process is created or starts
+# Enable events auditing generated when a process is created or starts
# Включить аудит событий, возникающих при создании или запуске процесса
-auditpol /set /subcategory:"{0CCE922B-69AE-11D9-BED3-505054503030}" /success:enable /failure:enable
+AuditProcess -Enable
+
+# Disable events auditing generated when a process is created or starts (default value)
+# Выключить аудит событий, возникающих при создании или запуске процесса (значение по умолчанию)
+# AuditProcess -Disable
<#
-Include command line in process creation events
-In order this feature to work events auditing must be enabled
+ Include command line in process creation events
+ In order this feature to work events auditing will be enabled ("AuditProcess -Enable" function)
-Включать командную строку в событиях создания процесса
-Необходимо включить аудит событий, чтобы работала данная опция
+ Включать командную строку в событиях создания процесса
+ Для того, чтобы работал данный функционал, будет включен аудит событий (функция "AuditProcess -Enable")
#>
-New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit -Name ProcessCreationIncludeCmdLine_Enabled -PropertyType DWord -Value 1 -Force
+AuditCommandLineProcess -Enable
+
+# Do not include command line in process creation events (default value)
+# Не включать командную строку в событиях создания процесса (значение по умолчанию)
+# AuditCommandLineProcess -Disable
<#
-Create "Process Creation" Event Viewer Custom View
-In order this feature to work events auditing and command line in process creation events must be enabled
+ Create "Process Creation" Event Viewer Custom View
+ In order this feature to work events auditing ("AuditProcess -Enable" function) and command line in process creation events will be enabled
-Создать настаиваемое представление "Создание процесса" в Просмотре событий
-Необходимо включить аудит событий и командной строки в событиях создания процесса, чтобы работала данная опция
+ Создать настаиваемое представление "Создание процесса" в Просмотре событий
+ Для того, чтобы работал данный функционал, буден включен аудит событий (функция "AuditProcess -Enable") и командной строки в событиях создания процесса
#>
-$XML = @"
-
-
-
-
-
-
- Process Creation
- Process Creation and Command-line Auditing Events
-
-
-
-
-
-
-
-
-"@
-if (-not (Test-Path -Path "$env:ProgramData\Microsoft\Event Viewer\Views"))
-{
- New-Item -Path "$env:ProgramData\Microsoft\Event Viewer\Views" -ItemType Directory -Force
-}
-$ProcessCreationFilePath = "$env:ProgramData\Microsoft\Event Viewer\Views\ProcessCreation.xml"
-# Saving ProcessCreation.xml in UTF-8 encoding
-# Сохраняем ProcessCreation.xml в кодировке UTF-8
-Set-Content -Path $ProcessCreationFilePath -Value (New-Object System.Text.UTF8Encoding).GetBytes($XML) -Encoding Byte -Force
-
-if ($RU)
-{
- [xml]$XML = Get-Content -Path $ProcessCreationFilePath
- $XML.ViewerConfig.QueryConfig.QueryNode.Name = "Создание процесса"
- $XML.ViewerConfig.QueryConfig.QueryNode.Description = "События содания нового процесса и аудит командной строки"
- $xml.Save("$env:ProgramData\Microsoft\Event Viewer\Views\ProcessCreation.xml")
-}
-
-# Log for all Windows PowerShell modules
-# Вести журнал для всех модулей Windows PowerShell
-if (-not (Test-Path -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames))
-{
- New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames -Force
-}
-New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging -Name EnableModuleLogging -PropertyType DWord -Value 1 -Force
-New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames -Name * -PropertyType String -Value * -Force
-
-# Log all PowerShell scripts input to the Windows PowerShell event log
-# Вести регистрацию всех вводимых сценариев PowerShell в журнале событий Windows PowerShell
-if (-not (Test-Path -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging))
-{
- New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging -Force
-}
-New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging -Name EnableScriptBlockLogging -PropertyType DWord -Value 1 -Force
-
-# Check apps and files within Microsofot Defender SmartScreen
-# Проверять приложения и файлы фильтром SmartScreen в Microsoft Defender
-New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name SmartScreenEnabled -PropertyType String -Value Off -Force
-
-# Prevent SmartScreen from marking files that have been downloaded from the Internet as unsafe (current user only)
-# Не позволять SmartScreen отмечать файлы, скачанные из интернета, как небезопасные (только для текущего пользователя)
-if (-not (Test-Path -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Attachments))
-{
- New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Attachments -Force
-}
-New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Attachments -Name SaveZoneInformation -PropertyType DWord -Value 1 -Force
-
-# Turn off Windows Script Host (current user only)
-# Отключить Windows Script Host (только для текущего пользователя)
-if (-not (Test-Path -Path "HKCU:\SOFTWARE\Microsoft\Windows Script Host\Settings"))
-{
- New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows Script Host\Settings" -Force
-}
-New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows Script Host\Settings" -Name Enabled -PropertyType DWord -Value 0 -Force
-#endregion Windows Defender & Security
+EventViewerCustomView -Enable
+
+# Remove "Process Creation" Event Viewer Custom View (default value)
+# Удалить настаиваемое представление "Создание процесса" в Просмотре событий (значение по умолчанию)
+# EventViewerCustomView -Disable
+
+# Enable logging for all Windows PowerShell modules
+# Включить ведение журнала для всех модулей Windows PowerShell
+PowerShellModulesLogging -Enable
+
+# Disable logging for all Windows PowerShell modules (default value)
+# Выключить ведение журнала для всех модулей Windows PowerShell (значение по умолчанию)
+# PowerShellModulesLogging -Disable
+
+# Enable logging for all PowerShell scripts input to the Windows PowerShell event log
+# Включить ведение журнала для всех вводимых сценариев PowerShell в журнале событий Windows PowerShell
+PowerShellScriptsLogging -Enable
+
+# Disable logging for all PowerShell scripts input to the Windows PowerShell event log (default value)
+# Выключить ведение журнала для всех вводимых сценариев PowerShell в журнале событий Windows PowerShell (значение по умолчанию)
+# PowerShellScriptsLogging -Disable
+
+# Disable apps and files checking within Microsofot Defender SmartScreen
+# Выключить проверку приложений и файлов фильтром SmartScreen в Microsoft Defender
+AppsSmartScreen -Disable
+
+# Enable apps and files checking within Microsofot Defender SmartScree (default value)
+# Включить проверку приложений и файлов фильтром SmartScreen в Microsoft Defender (значение по умолчанию)
+# AppsSmartScreen -Enable
+
+# Disable the Attachment Manager marking files that have been downloaded from the Internet as unsafe (current user only)
+# Выключить проверку Диспетчером вложений файлов, скачанных из интернета, как небезопасные (только для текущего пользователя)
+SaveZoneInformation -Disable
+
+# Enable the Attachment Manager marking files that have been downloaded from the Internet as unsafe (current user only) (default value)
+# Включить проверку Диспетчера вложений файлов, скачанных из интернета как небезопасные (только для текущего пользователя) (значение по умолчанию)
+# SaveZoneInformation -Enable
+
+<#
+ Disable Windows Script Host (current user only)
+ It becomes impossible to run .js and .vbs files
+
+ Отключить Windows Script Host (только для текущего пользователя)
+ Становится невозможным запустить файлы .js и .vbs
+#>
+WindowsScriptHost -Disable
+
+# Emable Windows Script Host (current user only) (default value)
+# Включить Windows Script Host (только для текущего пользователя) (значение по умолчанию)
+# WindowsScriptHost -Enable
+
+# Enable Windows Sandbox
+# Включить Windows Sandbox
+WindowsSandbox -Enable
+
+# Disable Windows Sandbox (default value)
+# Выключить Windows Sandbox (значение по умолчанию)
+# WindowsSandbox -Disable
+#endregion Microsoft Defender & Security
#region Context menu
# Add the "Extract all" item to Windows Installer (.msi) context menu
# Добавить пункт "Извлечь все" в контекстное меню Windows Installer (.msi)
-if (-not (Test-Path -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract\Command))
-{
- New-Item -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract\Command -Force
-}
-$Value = "{0}" -f 'msiexec.exe /a "%1" /qb TARGETDIR="%1 extracted"'
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract\Command -Name "(Default)" -PropertyType String -Value $Value -Force
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract -Name MUIVerb -PropertyType String -Value "@shell32.dll,-37514" -Force
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract -Name Icon -PropertyType String -Value "shell32.dll,-16817" -Force
+MSIExtractContext -Add
+
+# Remove the "Extract all" item from Windows Installer (.msi) context menu (default value)
+# Удалить пункт "Извлечь все" из контекстного меню Windows Installer (.msi) (значение по умолчанию)
+# MSIExtractContext -Remove
# Add the "Install" item to the .cab archives context menu
# Добавить пункт "Установить" в контекстное меню .cab архивов
-if (-not (Test-Path -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs\Command))
-{
- New-Item -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs\Command -Force
-}
-$Value = "{0}" -f "cmd /c DISM.exe /Online /Add-Package /PackagePath:`"%1`" /NoRestart & pause"
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs\Command -Name "(Default)" -PropertyType String -Value $Value -Force
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs -Name MUIVerb -PropertyType String -Value "@shell32.dll,-10210" -Force
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs -Name HasLUAShield -PropertyType String -Value "" -Force
+CABInstallContext -Add
+
+# Remove the "Install" item from the .cab archives context menu (default value)
+# Удалить пункт "Установить" из контекстного меню .cab архивов (значение по умолчанию)
+# CABInstallContext -Remove
# Add the "Run as different user" item to the .exe files types context menu
-# Добавить пункт "Запуск от имени другого пользователя" в контекстное меню .exe файлов
-Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\exefile\shell\runasuser -Name Extended -Force -ErrorAction Ignore
+# Добавить пункт "Запуск от имени другого пользователя" в контекстного меню .exe файлов
+RunAsDifferentUserContext -Add
+
+# Remove the "Run as different user" item from the .exe files types context menu (default value)
+# Удалить пункт "Запуск от имени другого пользователя" из контекстное меню .exe файлов (значение по умолчанию)
+# RunAsDifferentUserContext -Remove
# Hide the "Cast to Device" item from the context menu
# Скрыть пункт "Передать на устройство" из контекстного меню
-if (-not (Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked"))
-{
- New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Force
-}
-New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Name "{7AD84985-87B4-4a16-BE58-8B72A5B390F7}" -PropertyType String -Value "Play to menu" -Force
+CastToDeviceContext -Hide
+
+# Show the "Cast to Device" item in the context menu (default value)
+# Показывать пункт "Передать на устройство" в контекстном меню (значение по умолчанию)
+# CastToDeviceContext -Show
# Hide the "Share" item from the context menu
# Скрыть пункт "Отправить" (поделиться) из контекстного меню
-if (-not (Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked"))
-{
- New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Force
-}
-New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Name "{E2BF9676-5F8F-435C-97EB-11607A5BEDF7}" -PropertyType String -Value "" -Force
+ShareContext -Hide
+
+# Show the "Share" item in the context menu (default value)
+# Показывать пункт "Отправить" (поделиться) в контекстном меню (значение по умолчанию)
+# ShareContext -Show
# Hide the "Edit with Paint 3D" item from the context menu
# Скрыть пункт "Изменить с помощью Paint 3D" из контекстного меню
-$extensions = @(".bmp", ".gif", ".jpe", ".jpeg", ".jpg", ".png", ".tif", ".tiff")
-foreach ($extension in $extensions)
-{
- New-ItemProperty -Path "Registry::HKEY_CLASSES_ROOT\SystemFileAssociations\$extension\Shell\3D Edit" -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
-}
+EditWithPaint3DContext -Hide
+
+# Show the "Edit with Paint 3D" item in the context menu (default value)
+# Показывать пункт "Изменить с помощью Paint 3D" в контекстном меню (значение по умолчанию)
+# EditWithPaint3DContext -Show
# Hide the "Print" item from the .bat and .cmd context menu
# Скрыть пункт "Печать" из контекстного меню .bat и .cmd файлов
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\batfile\shell\print -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\cmdfile\shell\print -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+PrintCMDContext -Hide
+
+# Show the "Print" item in the .bat and .cmd context menu (default value)
+# Показывать пункт "Печать" в контекстном меню .bat и .cmd файлов (значение по умолчанию)
+# PrintCMDContext -Show
# Hide the "Include in Library" item from the context menu
# Скрыть пункт "Добавить в библиотеку" из контекстного меню
-New-ItemProperty -Path "Registry::HKEY_CLASSES_ROOT\Folder\shellex\ContextMenuHandlers\Library Location" -Name "(Default)" -PropertyType String -Value "-{3dad6c5d-2167-4cae-9914-f99e41c12cfa}" -Force
+IncludeInLibraryContext -Hide
+
+# Show the "Include in Library" item in the context menu (default value)
+# Показывать пункт "Добавить в библиотеку" в контекстном меню (значение по умолчанию)
+# IncludeInLibraryContext -Show
# Hide the "Send to" item from the folders context menu
# Скрыть пункт "Отправить" из контекстного меню папок
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\SendTo -Name "(Default)" -PropertyType String -Value "-{7BA4C740-9E81-11CF-99D3-00AA004AE837}" -Force
+SendToContext -Hide
+
+# Show the "Send to" item in the folders context menu (default value)
+# Показывать пункт "Отправить" в контекстном меню папок (значение по умолчанию)
+# SendToContext -Show
# Hide the "Turn on BitLocker" item from the context menu
# Скрыть пункт "Включить BitLocker" из контекстного меню
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\encrypt-bde -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\encrypt-bde-elev -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\manage-bde -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\resume-bde -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\resume-bde-elev -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
-New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\unlock-bde -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+BitLockerContext -Hide
+
+# Show the "Turn on BitLocker" item in the context menu (default value)
+# Показывать пункт "Включить BitLocker" в контекстном меню (значение по умолчанию)
+# BitLockerContext -Show
# Remove the "Bitmap image" item from the "New" context menu
# Удалить пункт "Точечный рисунок" из контекстного меню "Создать"
-Remove-Item -Path Registry::HKEY_CLASSES_ROOT\.bmp\ShellNew -Force -ErrorAction Ignore
+BitmapImageNewContext -Remove
+
+# Add the "Bitmap image" item in the "New" context menu (default value)
+# Восстановить пункт "Точечный рисунок" в контекстного меню "Создать" (значение по умолчанию)
+# BitmapImageNewContext -Add
# Remove the "Rich Text Document" item from the "New" context menu
# Удалить пункт "Документ в формате RTF" из контекстного меню "Создать"
-Remove-Item -Path Registry::HKEY_CLASSES_ROOT\.rtf\ShellNew -Force -ErrorAction Ignore
+RichTextDocumentNewContext -Remove
+
+# Add the "Rich Text Document" item in the "New" context menu (default value)
+# Восстановить пункт "Документ в формате RTF" в контекстного меню "Создать" (значение по умолчанию)
+# RichTextDocumentNewContext -Add
# Remove the "Compressed (zipped) Folder" item from the "New" context menu
# Удалить пункт "Сжатая ZIP-папка" из контекстного меню "Создать"
-Remove-Item -Path Registry::HKEY_CLASSES_ROOT\.zip\CompressedFolder\ShellNew -Force -ErrorAction Ignore
+CompressedFolderNewContext -Remove
+
+# Add the "Compressed (zipped) Folder" item from the "New" context menu (default value)
+# Восстановить пункт "Сжатая ZIP-папка" в контекстном меню "Создать" (значение по умолчанию)
+# CompressedFolderNewContext -Add
+
+# Enable the "Open", "Print", and "Edit" context menu items for more than 15 items selected
+# Включить элементы контекстного меню "Открыть", "Изменить" и "Печать" при выделении более 15 элементов
+MultipleInvokeContext -Enable
-# Make the "Open", "Print", and "Edit" context menu items available, when more than 15 items selected
-# Сделать доступными элементы контекстного меню "Открыть", "Изменить" и "Печать" при выделении более 15 элементов
-New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name MultipleInvokePromptMinimum -PropertyType DWord -Value 300 -Force
+# Disable the "Open", "Print", and "Edit" context menu items for more than 15 items selected (default value)
+# Отключить элементы контекстного меню "Открыть", "Изменить" и "Печать" при выделении более 15 элементов (значение по умолчанию)
+# MultipleInvokeContext -Disable
-# Hide the "Look for an app in the Microsoft Store" item in "Open with" dialog
+# Hide the "Look for an app in the Microsoft Store" item in the "Open with" dialog
# Скрыть пункт "Поиск приложения в Microsoft Store" в диалоге "Открыть с помощью"
-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 NoUseStoreOpenWith -PropertyType DWord -Value 1 -Force
+UseStoreOpenWith -Hide
+
+# Show the "Look for an app in the Microsoft Store" item in the "Open with" dialog (default value)
+# Отображать пункт "Поиск приложения в Microsoft Store" в диалоге "Открыть с помощью" (значение по умолчанию)
+# UseStoreOpenWith -Show
# Hide the "Previous Versions" tab from files and folders context menu and also the "Restore previous versions" context menu item
# Скрыть вкладку "Предыдущие версии" в свойствах файлов и папок, а также пункт контекстного меню "Восстановить прежнюю версию"
-New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name NoPreviousVersionsPage -PropertyType DWord -Value 1 -Force
+PreviousVersionsPage -Hide
+
+# Show the "Previous Versions" tab from files and folders context menu and also the "Restore previous versions" context menu item (default value)
+# Отображать вкладку "Предыдущие версии" в свойствах файлов и папок, а также пункт контекстного меню "Восстановить прежнюю версию" (значение по умолчанию)
+# PreviousVersionsPage -Show
#endregion Context menu
-#region Refresh
-$UpdateExplorer = @{
- Namespace = "WinAPI"
- Name = "UpdateExplorer"
- Language = "CSharp"
- MemberDefinition = @"
-private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
-private const int WM_SETTINGCHANGE = 0x1a;
-private const int SMTO_ABORTIFHUNG = 0x0002;
-
-[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
-static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);
-[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
-private static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, string lParam, int fuFlags, int uTimeout, IntPtr lpdwResult);
-[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = false)]
-private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
-public static void Refresh()
-{
- // Update desktop icons
- // Обновить иконки рабочего стола
- SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
- // Update environment variables
- // Обновить переменные среды
- SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, null, SMTO_ABORTIFHUNG, 100, IntPtr.Zero);
- // Update taskbar
- // Обновить панель задач
- SendNotifyMessage(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, "TraySettings");
-}
-
-private static readonly IntPtr hWnd = new IntPtr(65535);
-private const int Msg = 273;
-// Virtual key ID of the F5 in File Explorer
-// Виртуальный код клавиши F5 в проводнике
-private static readonly UIntPtr UIntPtr = new UIntPtr(41504);
-
-[DllImport("user32.dll", SetLastError=true)]
-public static extern int PostMessageW(IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam);
-public static void PostMessage()
-{
- // Simulate pressing F5 to refresh the desktop
- // Симулировать нажатие F5 для обновления рабочего стола
- PostMessageW(hWnd, Msg, UIntPtr, IntPtr.Zero);
-}
-"@
-}
-if (-not ("WinAPI.UpdateExplorer" -as [type]))
-{
- Add-Type @UpdateExplorer
-}
-
-# Simulate pressing F5 to refresh the desktop
-# Симулировать нажатие F5 для обновления рабочего стола
-[WinAPI.UpdateExplorer]::PostMessage()
-# Refresh desktop icons, environment variables, taskbar
-# Обновить иконки рабочего стола, переменные среды, панель задач
-[WinAPI.UpdateExplorer]::Refresh()
-#endregion Refresh
+<#
+ Simulate pressing F5 to refresh the desktop
+ Refresh desktop icons, environment variables, taskbar
+ Restart the Start menu
+
+ Симулировать нажатие F5 для обновления рабочего стола
+ Обновить иконки рабочего стола, переменные среды, панель задач
+ Перезапустить меню "Пуск"
+#>
+Refresh
# Errors output
# Вывод ошибок
-if ($Error)
-{
- ($Error | ForEach-Object -Process {
- if ($RU)
- {
- [PSCustomObject] @{
- Строка = $_.InvocationInfo.ScriptLineNumber
- "Ошибки/предупреждения" = $_.Exception.Message
- }
- }
- else
- {
- [PSCustomObject] @{
- Line = $_.InvocationInfo.ScriptLineNumber
- "Errors/Warnings" = $_.Exception.Message
- }
- }
- } | Sort-Object -Property Line | Format-Table -AutoSize -Wrap | Out-String).Trim()
-}
+Errors
diff --git a/LTSC/Sophia.psd1 b/LTSC/Sophia.psd1
new file mode 100644
index 00000000..21f0596b
Binary files /dev/null and b/LTSC/Sophia.psd1 differ
diff --git a/LTSC/Sophia.psm1 b/LTSC/Sophia.psm1
new file mode 100644
index 00000000..58f8c88a
--- /dev/null
+++ b/LTSC/Sophia.psm1
@@ -0,0 +1,8376 @@
+<#
+ .SYNOPSIS
+ "Windows 10 Sophia Script" (LTSC version) is a PowerShell module for Windows 10 fine-tuning and automating the routine tasks
+
+ Version: v5.0
+ Date: 29.12.2020
+ Copyright (c) 2020 farag & oZ-Zo
+
+ Thanks to all https://forum.ru-board.com members involved
+
+ .DESCRIPTION
+ Supported Windows 10 versions: 1809 Enterprise LTSC, 17763 build, 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/en/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
+#>
+
+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 17763)
+ {
+ $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
+
+ # Turn off Controlled folder access to let the script proceed
+ # Выключить контролируемый доступ к папкам
+ switch ((Get-MpPreference).EnableControlledFolderAccess -eq 1)
+ {
+ $true
+ {
+ Write-Warning -Message $Localization.ControlledFolderAccessDisabled
+ Set-MpPreference -EnableControlledFolderAccess Disabled
+
+ # Open "Ransomware protection" page
+ # Открыть раздел "Защита от программ-шатажистов"
+ Start-Process -FilePath windowsdefender://RansomwareProtection
+ }
+ }
+}
+#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 "Connected User Experiences and Telemetry" service (DiagTrack)
+ Отключить/включить службу "Функциональные возможности для подключенных пользователей и телеметрия" (DiagTrack)
+
+ .PARAMETER Disable
+ Disable the DiagTrack service
+ Отключить службу DiagTrack
+
+ .PARAMETER Enable
+ Enable the DiagTrack service
+ Включить службу DiagTrack
+
+ .EXAMPLE
+ TelemetryService -Disable
+
+ .EXAMPLE
+ TelemetryService -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function TelemetryService
+{
+ 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
+ }
+ "Disable"
+ {
+ Get-Service -Name DiagTrack | Stop-Service -Force
+ Get-Service -Name DiagTrack | Set-Service -StartupType Disabled
+ }
+ }
+}
+
+<#
+ .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"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 0 -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
+#>
+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 = '
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ '
+ #endregion XAML Markup
+
+ $Reader = (New-Object -TypeName System.Xml.XmlNodeReader -ArgumentList $XAML)
+ $Form = [Windows.Markup.XamlReader]::Load($Reader)
+ $XAML.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | ForEach-Object -Process {
+ Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name) -Scope Global
+ }
+
+ #region Functions
+ function Get-CheckboxClicked
+ {
+ [CmdletBinding()]
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ValueFromPipeline = $true
+ )]
+ [ValidateNotNull()]
+ $CheckBox
+ )
+
+ $Task = $CheckBox.Parent.Children[1].Text
+ if ($CheckBox.IsChecked)
+ {
+ [void]$Tasks.Add($Task)
+ }
+ else
+ {
+ [void]$Tasks.Remove($Task)
+ }
+ if ($Tasks.Count -gt 0)
+ {
+ $Button.IsEnabled = $true
+ }
+ else
+ {
+ $Button.IsEnabled = $false
+ }
+ }
+
+ function DisableButton
+ {
+ [void]$Window.Close()
+ $OFS = "|"
+ Get-ScheduledTask | Where-Object -FilterScript {$_.TaskName -cmatch $Tasks} | Disable-ScheduledTask
+ $OFS = " "
+ }
+
+ function EnableButton
+ {
+ [void]$Window.Close()
+ $OFS = "|"
+ Get-ScheduledTask | Where-Object -FilterScript {$_.TaskName -cmatch $Tasks} | Enable-ScheduledTask
+ $OFS = " "
+ }
+
+ function Add-TaskControl
+ {
+ [CmdletBinding()]
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ValueFromPipeline = $true
+ )]
+ [ValidateNotNull()]
+ [string]
+ $Task
+ )
+
+ $CheckBox = New-Object -TypeName System.Windows.Controls.CheckBox
+ $CheckBox.Add_Click({Get-CheckboxClicked -CheckBox $_.Source})
+
+ $TextBlock = New-Object -TypeName System.Windows.Controls.TextBlock
+ $TextBlock.Text = $Task
+
+ $StackPanel = New-Object -TypeName System.Windows.Controls.StackPanel
+ [void]$StackPanel.Children.Add($CheckBox)
+ [void]$StackPanel.Children.Add($TextBlock)
+
+ [void]$PanelContainer.Children.Add($StackPanel)
+
+ $CheckBox.IsChecked = $false
+
+ # If task checked, add to the array list to remove
+ # Если задача выделена, то добавить в массив для удаления
+ if ($CheckedScheduledTasks | Where-Object -FilterScript {$Task -like $_})
+ {
+ $CheckBox.IsChecked = $true
+ [void]$Tasks.Add($Task)
+ }
+ }
+ #endregion Functions
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ #region Events Handlers
+ $OptionalTasks = New-Object -TypeName System.Collections.ArrayList($null)
+ # Window Loaded Event
+ $Window.Add_Loaded({
+ $OFS = "|"
+ $OptionalTasks = @(Get-ScheduledTask | Where-Object -FilterScript {($_.State -eq "Disabled") -and ($_.TaskName -in $CheckedScheduledTasks)})
+ if ($OptionalTasks.Count -gt 0)
+ {
+ $OptionalTasks | ForEach-Object -Process {
+ Add-TaskControl -Task $_.TaskName
+ }
+
+ $Button.Content = $Localization.Enable
+ }
+ else
+ {
+ Write-Verbose -Message $Localization.NoData -Verbose
+ $Form.Close()
+ }
+ $OFS = " "
+ })
+
+ # Button Click Event
+ $Button.Add_Click({EnableButton})
+ #endregion Events Handlers
+ }
+ "Disable"
+ {
+ #region Events Handlers
+ $OptionalTasks = New-Object System.Collections.ArrayList($null)
+ # Window Loaded Event
+ $Window.Add_Loaded({
+ $OFS = "|"
+ $OptionalTasks = @(Get-ScheduledTask | Where-Object -FilterScript {($_.State -eq "Ready") -and ($_.TaskName -in $CheckedScheduledTasks)})
+ if ($OptionalTasks.Count -gt 0)
+ {
+ $OptionalTasks | ForEach-Object -Process {
+ Add-TaskControl -Task $_.TaskName
+ }
+
+ $Button.Content = $Localization.Disable
+ }
+ else
+ {
+ Write-Verbose -Message $Localization.NoData -Verbose
+ $Form.Close()
+ }
+ $OFS = " "
+ })
+
+ # Button Click Event
+ $Button.Add_Click({DisableButton})
+ #endregion Events Handlers
+ }
+ }
+
+ Write-Verbose -Message $Localization.DialogBoxOpening -Verbose
+
+ $Window.Title = $Localization.ScheduledTasks
+ $Form.ShowDialog() | Out-Null
+}
+
+<#
+ .SYNOPSIS
+ Do not use/use sign-in info to automatically finish setting up device and reopen apps after an update or restart
+ Не использовать/использовать данные для входа для автоматического завершения настройки устройства и открытия приложений после перезапуска или обновления
+
+ .PARAMETER Disable
+ Do not use sign-in info to automatically finish setting up device and reopen apps after an update or restart
+ Не использовать данные для входа для автоматического завершения настройки устройства и открытия приложений после перезапуска или обновления
+
+ .PARAMETER Enable
+ Use sign-in info to automatically finish setting up device and reopen apps after an update or restart
+ Использовать данные для входа для автоматического завершения настройки устройства и открытия приложений после перезапуска или обновления
+
+ .EXAMPLE
+ SigninInfo -Disable
+
+ .EXAMPLE
+ SigninInfo -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function SigninInfo
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ $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
+ }
+ "Enable"
+ {
+ $SID = (Get-CimInstance -ClassName Win32_UserAccount | Where-Object -FilterScript {$_.Name -eq $env:USERNAME}).SID
+ Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\UserARSO\$SID" -Name OptOut -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Do not let/let websites provide locally relevant content by accessing language list
+ Не позволять/позволять веб-сайтам предоставлять местную информацию за счет доступа к списку языков
+
+ .PARAMETER Disable
+ Do not let websites provide locally relevant content by accessing language list
+ Не позволять веб-сайтам предоставлять местную информацию за счет доступа к списку языков
+
+ .PARAMETER Enable
+ Let websites provide locally relevant content by accessing language list
+ Позволять веб-сайтам предоставлять местную информацию за счет доступа к списку языков
+
+ .EXAMPLE
+ LanguageListAccess -Disable
+
+ .EXAMPLE
+ LanguageListAccess -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function LanguageListAccess
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path "HKCU:\Control Panel\International\User Profile" -Name HttpAcceptLanguageOptOut -PropertyType DWord -Value 1 -Force
+ }
+ "Enable"
+ {
+ Remove-ItemProperty -Path "HKCU:\Control Panel\International\User Profile" -Name HttpAcceptLanguageOptOut -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Do not allow/allow apps to use advertising ID
+ Не разрешать/разрешать приложениям использовать идентификатор рекламы
+
+ .PARAMETER Disable
+ Do not allow apps to use advertising ID
+ Не разрешать приложениям использовать идентификатор рекламы
+
+ .PARAMETER Enable
+ Do not allow apps to use advertising ID
+ Не разрешать приложениям использовать идентификатор рекламы
+
+ .EXAMPLE
+ AdvertisingID -Disable
+
+ .EXAMPLE
+ AdvertisingID -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function AdvertisingID
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ 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
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo -Name Enabled -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Do not let/let apps on other devices open and message apps on this device, and vice versa
+ Не разрешать/разрешать приложениям на других устройствах запускать приложения и отправлять сообщения на этом устройстве и наоборот
+
+ .PARAMETER Disable
+ Do not let apps on other devices open and message apps on this device, and vice versa
+ Не разрешать/разрешать приложениям на других устройствах запускать приложения и отправлять сообщения на этом устройстве и наоборот
+
+ .PARAMETER Enable
+ Let apps on other devices open and message apps on this device, and vice versa
+ разрешать приложениям на других устройствах запускать приложения и отправлять сообщения на этом устройстве и наоборот
+
+ .EXAMPLE
+ ShareAcrossDevices -Disable
+
+ .EXAMPLE
+ ShareAcrossDevices -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function ShareAcrossDevices
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\CDP -Name RomeSdkChannelUserAuthzPolicy -PropertyType DWord -Value 1 -Force
+ }
+ "Disable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\CDP -Name RomeSdkChannelUserAuthzPolicy -PropertyType DWord -Value 0 -Force
+ }
+ }
+}
+#endregion Privacy & Telemetry
+
+#region UI & Personalization
+<#
+ .SYNOPSIS
+ Show/hide "This PC" on Desktop
+ Отображать/скрывать "Этот компьютер" на рабочем столе
+
+ .PARAMETER Hide
+ Show "This PC" on Desktop
+ Отображать "Этот компьютер" на рабочем столе
+
+ .PARAMETER Show
+ Hide "This PC" on Desktop
+ Скрывать "Этот компьютер" на рабочем столе
+
+ .EXAMPLE
+ ThisPC -Hide
+
+ .EXAMPLE
+ ThisPC -Show
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function ThisPC
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Show"
+ {
+ if (-not (Test-Path -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel))
+ {
+ New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Force
+ }
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -PropertyType DWord -Value 0 -Force
+ }
+ "Hide"
+ {
+ Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Do not use/use check boxes to select items
+ Не использовать/использовать флажки для выбора элементов
+
+ .PARAMETER Disable
+ Do not use check boxes to select items
+ Не использовать флажки для выбора элементов
+
+ .PARAMETER Enable
+ Use check boxes to select items
+ Использовать флажки для выбора элементов
+
+ .EXAMPLE
+ CheckBoxes -Disable
+
+ .EXAMPLE
+ CheckBoxes -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function CheckBoxes
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name AutoCheckSelect -PropertyType DWord -Value 1 -Force
+ }
+ "Disable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name AutoCheckSelect -PropertyType DWord -Value 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Show/do not show hidden files, folders, and drives
+ Отображать/не отображать скрытые файлы, папки и диски
+
+ .PARAMETER Enable
+ Show hidden files, folders, and drives
+ Отображать скрытые файлы, папки и диски
+
+ .PARAMETER Disable
+ Do not show hidden files, folders, and drives
+ Не отображать скрытые файлы, папки и диски
+
+ .EXAMPLE
+ HiddenItems -Enable
+
+ .EXAMPLE
+ HiddenItems -Disable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function HiddenItems
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name Hidden -PropertyType DWord -Value 1 -Force
+ }
+ "Disable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name Hidden -PropertyType DWord -Value 2 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Show/hide file name extensions
+ Отображать/скрывать расширения имён файлов
+
+ .PARAMETER Show
+ Show file name extensions
+ Отображать расширения имён файлов
+
+ .PARAMETER Hide
+ Hide file name extensions
+ Скрывать расширения имён файлов
+
+ .EXAMPLE
+ FileExtensions -Show
+
+ .EXAMPLE
+ FileExtensions -Hide
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function FileExtensions
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Show"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideFileExt -PropertyType DWord -Value 0 -Force
+ }
+ "Hide"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideFileExt -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Show/hide folder merge conflicts
+ Отображать/скрывать конфликт слияния папок
+
+ .PARAMETER Show
+ Show folder merge conflicts
+ Отображать конфликт слияния папок
+
+ .PARAMETER Hide
+ Hide folder merge conflicts
+ Скрывать конфликт слияния папок
+
+ .EXAMPLE
+ MergeConflicts -Show
+
+ .EXAMPLE
+ MergeConflicts -Hide
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+
+function MergeConflicts
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Show"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideMergeConflicts -PropertyType DWord -Value 1 -Force
+ }
+ "Hide"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideMergeConflicts -PropertyType DWord -Value 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Open File Explorer to "This PC" or "Quick access"
+ Открывать проводник для "Этот компьютер" или "Быстрый доступ"
+
+ .PARAMETER ThisPC
+ Open File Explorer to "This PC"
+ Открывать проводник для "Этот компьютер"
+
+ .PARAMETER QuickAccess
+ Open File Explorer to "Quick access"
+ Открывать проводник для "Быстрый доступ"
+
+ .EXAMPLE
+ OpenFileExplorerTo -ThisPC
+
+ .EXAMPLE
+ OpenFileExplorerTo -QuickAccess
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function OpenFileExplorerTo
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "ThisPC"
+ )]
+ [switch]
+ $ThisPC,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "QuickAccess"
+ )]
+ [switch]
+ $QuickAccess
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "ThisPC"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name LaunchTo -PropertyType DWord -Value 1 -Force
+ }
+ "QuickAccess"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name LaunchTo -PropertyType DWord -Value 2 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide Task View button on the taskbar
+ Скрыть кнопку Просмотра задач
+
+ .PARAMETER Hide
+ Show Task View button on the taskbar
+ Не показывать кнопку Просмотра задач
+
+ .PARAMETER Show
+ Do not show Task View button on the taskbar
+ Не показывать кнопку Просмотра задач
+
+ .EXAMPLE
+ TaskViewButton -Hide
+
+ .EXAMPLE
+ TaskViewButton -Show
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+
+function TaskViewButton
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowTaskViewButton -PropertyType DWord -Value 0 -Force
+ }
+ "Show"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowTaskViewButton -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show People button on the taskbar
+ Скрывать/показывать панель "Люди" на панели задач
+
+ .PARAMETER Hide
+ Hide People button on the taskbar
+ Скрывать панель "Люди" на панели задач
+
+ .PARAMETER Show
+ Show People button on the taskbar
+ Показывать панель "Люди" на панели задач
+
+ .EXAMPLE
+ PeopleTaskbar -Hide
+
+ .EXAMPLE
+ PeopleTaskbar -Show
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+
+function PeopleTaskbar
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ 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"
+ {
+ 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 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Show/hide seconds on the taskbar clock
+ Отображать/скрывать секунды в системных часах на панели задач
+
+ .PARAMETER Hide
+ Hide seconds on the taskbar clock
+ Скрывать секунды в системных часах на панели задач
+
+ .PARAMETER Show
+ Show seconds on the taskbar clock
+ Отображать секунды в системных часах на панели задач
+
+ .EXAMPLE
+ SecondsInSystemClock -Hide
+
+ .EXAMPLE
+ SecondsInSystemClock -Show
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function SecondsInSystemClock
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSecondsInSystemClock -PropertyType DWord -Value 0 -Force
+ }
+ "Show"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSecondsInSystemClock -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ When I snap a window, do not show/show what I can snap next to it
+ При прикреплении окна не показывать/показывать, что можно прикрепить рядом с ним
+
+ .PARAMETER Disable
+ When I snap a window, do not show what I can snap next to it
+ При прикреплении окна не показывать, что можно прикрепить рядом с ним
+
+ .PARAMETER Enable
+ When I snap a window, show what I can snap next to it
+ При прикреплении окна не показывать/показывать, что можно прикрепить рядом с ним
+
+ .EXAMPLE
+ SnapAssist -Disable
+
+ .EXAMPLE
+ SnapAssist -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function SnapAssist
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SnapAssist -PropertyType DWord -Value 0 -Force
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SnapAssist -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Always open the file transfer dialog box in the detailed/compact mode
+ Всегда открывать диалоговое окно передачи файлов в развернутом/свернутом виде
+
+ .PARAMETER Detailed
+ Always open the file transfer dialog box in the detailed mode
+ Всегда открывать диалоговое окно передачи файлов в развернутом виде
+
+ .PARAMETER Compact
+ Always open the file transfer dialog box in the compact mode
+ Всегда открывать диалоговое окно передачи файлов в развернутом виде
+
+ .EXAMPLE
+ FileTransferDialog -Detailed
+
+ .EXAMPLE
+ FileTransferDialog -Compact
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function FileTransferDialog
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Detailed"
+ )]
+ [switch]
+ $Detailed,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Compact"
+ )]
+ [switch]
+ $Compact
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Detailed"
+ {
+ 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
+ }
+ "Compact"
+ {
+ 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 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Always expand/minimize the ribbon in the File Explorer
+ Всегда разворачивать/сворачивать ленту в проводнике
+
+ .PARAMETER Expanded
+ Always expand the ribbon in the File Explorer
+ Всегда разворачивать ленту в проводнике
+
+ .PARAMETER Minimized
+ Always minimize the ribbon in the File Explorer
+ Всегда разворачивать ленту в проводнике
+
+ .EXAMPLE
+ FileExplorerRibbon -Expanded
+
+ .EXAMPLE
+ FileExplorerRibbon -Minimized
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function FileExplorerRibbon
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Expanded"
+ )]
+ [switch]
+ $Expanded,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Minimized"
+ )]
+ [switch]
+ $Minimized
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Expanded"
+ {
+ 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
+ }
+ "Minimized"
+ {
+ 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 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Display/do not display recycle bin files delete confirmation
+ Запрашивать/не запрашивать подтверждение на удаление файлов в корзину
+
+ .PARAMETER Disable
+ Display/do not display recycle bin files delete confirmation
+ Запрашивать/не запрашивать подтверждение на удаление файлов в корзину
+
+ .PARAMETER Enable
+ Display/do not display recycle bin files delete confirmation
+ Запрашивать/не запрашивать подтверждение на удаление файлов в корзину
+
+ .EXAMPLE
+ RecycleBinDeleteConfirmation -Disable
+
+ .EXAMPLE
+ RecycleBinDeleteConfirmation -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function RecycleBinDeleteConfirmation
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ $UpdateDesktop = @{
+ Namespace = "WinAPI"
+ Name = "UpdateDesktop"
+ Language = "CSharp"
+ MemberDefinition = @"
+private static readonly IntPtr hWnd = new IntPtr(65535);
+private const int Msg = 273;
+// Virtual key ID of the F5 in File Explorer
+// Виртуальный код клавиши F5 в проводнике
+private static readonly UIntPtr UIntPtr = new UIntPtr(41504);
+
+[DllImport("user32.dll", SetLastError=true)]
+public static extern int PostMessageW(IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam);
+public static void PostMessage()
+{
+ // F5 pressing simulation to refresh the desktop
+ // Симуляция нажатия F5 для обновления рабочего стола
+ PostMessageW(hWnd, Msg, UIntPtr, IntPtr.Zero);
+}
+"@
+ }
+ if (-not ("WinAPI.UpdateDesktop" -as [type]))
+ {
+ Add-Type @UpdateDesktop
+ }
+
+ $ShellState = Get-ItemPropertyValue -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShellState
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ $ShellState[4] = 55
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShellState -PropertyType Binary -Value $ShellState -Force
+ }
+ "Enable"
+ {
+ $ShellState[4] = 51
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShellState -PropertyType Binary -Value $ShellState -Force
+ }
+ }
+
+ # Send F5 pressing simulation to refresh the desktop
+ # Симулировать нажатие F5 для обновления рабочего стола
+ [WinAPI.UpdateDesktop]::PostMessage()
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "3D Objects" folder in "This PC" and "Quick access"
+ Скрыть/отобразить папку "Объемные объекты" в "Этот компьютер" и панели быстрого доступа
+
+ .PARAMETER Show
+ Show the "3D Objects" folder in "This PC" and "Quick access"
+ Отобразить папку "Объемные объекты" в "Этот компьютер" и панели быстрого доступа
+
+ .PARAMETER Hide
+ Hide the "3D Objects" folder in "This PC" and "Quick access"
+ Скрыть папку "Объемные объекты" в "Этот компьютер" и панели быстрого доступа
+
+ .EXAMPLE
+ 3DObjects -Show
+
+ .EXAMPLE
+ 3DObjects -Hide
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function 3DObjects
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ 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
+ }
+ "Show"
+ {
+ Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FolderDescriptions\{31C0DD25-9439-4F12-BF41-7FF4EDA38722}\PropertyBag" -Name ThisPCPolicy -Force -ErrorAction SilentlyContinue
+ }
+ }
+
+ # Save all opened folders in order to restore them after File Explorer restart
+ # Сохранить все открытые папки, чтобы восстановить их после перезапуска проводника
+ Clear-Variable -Name OpenedFolders -Force -ErrorAction Ignore
+ $OpenedFolders = {(New-Object -ComObject Shell.Application).Windows() | ForEach-Object -Process {$_.Document.Folder.Self.Path}}.Invoke()
+
+ # In order for the changes to take effect the File Explorer process has to be restarted
+ # Чтобы изменения вступили в силу, необходимо перезапустить процесс проводника
+ Stop-Process -Name explorer -Force
+
+ # Restoring closed folders
+ # Восстановить закрытые папки
+ foreach ($OpenedFolder in $OpenedFolders)
+ {
+ if (Test-Path -Path $OpenedFolder)
+ {
+ Invoke-Item -Path $OpenedFolder
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show frequently used folders in "Quick access"
+ Скрывать/показывать недавно используемые папки на панели быстрого доступа
+
+ .PARAMETER Show
+ Show frequently used folders in "Quick access"
+ Показывать недавно используемые папки на панели быстрого доступа
+
+ .PARAMETER Hide
+ Hide frequently used folders in "Quick access"
+ Скрывать недавно используемые папки на панели быстрого доступа
+
+ .EXAMPLE
+ QuickAccessFrequentFolders -Show
+
+ .EXAMPLE
+ QuickAccessFrequentFolders -Hide
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function QuickAccessFrequentFolders
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShowFrequent -PropertyType DWord -Value 0 -Force
+ }
+ "Show"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShowFrequent -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show recently used files in Quick access
+ Скрывать/показывать недавно использовавшиеся файлы на панели быстрого доступа
+
+ .PARAMETER Show
+ Show recently used files in Quick access
+ Показывать недавно использовавшиеся файлы на панели быстрого доступа
+
+ .PARAMETER Hide
+ Hide recently used files in Quick access
+ Скрывать недавно использовавшиеся файлы на панели быстрого доступа
+
+ .EXAMPLE
+ QuickAccessRecentFiles -Show
+
+ .EXAMPLE
+ QuickAccessRecentFiles -Hide
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function QuickAccessRecentFiles
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShowRecent -PropertyType DWord -Value 0 -Force
+ }
+ "Show"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShowRecent -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the search box or search icon on the taskbar
+ Скрыть/показать поле или значок поиска на панели задач
+
+ .PARAMETER SearchBox
+ Show the search box on the taskbar
+ Показать поле поиска на панели задач
+
+ .PARAMETER SearchIcon
+ Show the search icon on the taskbar
+ Показать значок поиска на панели задач
+
+ .PARAMETER Hide
+ Hide the search box on the taskbar
+ Скрывать поле поиска на панели задач
+
+ .EXAMPLE
+ TaskbarSearch -SearchBox
+
+ .EXAMPLE
+ TaskbarSearch -SearchIcon
+
+ .EXAMPLE
+ TaskbarSearch -Hide
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function TaskbarSearch
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "ShowIcon"
+ )]
+ [switch]
+ $SearchIcon,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "SearchBox"
+ )]
+ [switch]
+ $SearchBox
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search -Name SearchboxTaskbarMode -PropertyType DWord -Value 0 -Force
+ }
+ "SearchIcon"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search -Name SearchboxTaskbarMode -PropertyType DWord -Value 1 -Force
+ }
+ "SearchBox"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search -Name SearchboxTaskbarMode -PropertyType DWord -Value 2 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Always show/hide all icons in the notification area
+ Всегда отображать/скрывать все значки в области уведомлений
+
+ .PARAMETER Show
+ Always show all icons in the notification area
+ Всегда отображать все значки в области уведомлений
+
+ .PARAMETER Hide
+ Hide all icons in the notification area
+ Скрывать все значки в области уведомлений
+
+ .EXAMPLE
+ TrayIcons -Show
+
+ .EXAMPLE
+ TrayIcons -Hide
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function TrayIcons
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name EnableAutoTray -PropertyType DWord -Value 1 -Force
+ }
+ "Show"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name EnableAutoTray -PropertyType DWord -Value 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ View the Control Panel icons by: large icons/category
+ Просмотр иконок Панели управления как: крупные значки/категория
+
+ .PARAMETER LargeIcons
+ View the Control Panel icons by: large icons
+ Просмотр иконок Панели управления как: крупные значки
+
+ .PARAMETER Category
+ View the Control Panel icons by: category
+ Просмотр иконок Панели управления как: категория
+
+ .EXAMPLE
+ ControlPanelView -LargeIcons
+
+ .EXAMPLE
+ ControlPanelView -Category
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function ControlPanelView
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "LargeIcons"
+ )]
+ [switch]
+ $LargeIcons,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Category"
+ )]
+ [switch]
+ $Category
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "LargeIcons"
+ {
+ 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
+ }
+ "Category"
+ {
+ 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 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Set the Windows mode color scheme to the light/dark
+ Установить режим цвета для Windows на светлый/темный
+
+ .PARAMETER Light
+ Set the Windows mode color scheme to the light
+ Установить режим цвета для Windows на светлый
+
+ .PARAMETER Dark
+ Set the Windows mode color scheme to the dark
+ Установить режим цвета для Windows на темный
+
+ .EXAMPLE
+ WindowsColorScheme -Light
+
+ .EXAMPLE
+ WindowsColorScheme -Dark
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function WindowsColorScheme
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Light"
+ )]
+ [switch]
+ $Light,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Dark"
+ )]
+ [switch]
+ $Dark
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Light"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name SystemUsesLightTheme -PropertyType DWord -Value 1 -Force
+ }
+ "Dark"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name SystemUsesLightTheme -PropertyType DWord -Value 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Set the default app mode color scheme to the light/dark
+ Установить цвет режима приложений по умолчанию на светлый/темный
+
+ .PARAMETER Light
+ Set the default app mode color scheme to the light
+ Установить цвет режима приложений по умолчанию на светлый
+
+ .PARAMETER Dark
+ Set the default app mode color scheme to the dark
+ Установить цвет режима приложений по умолчанию на темный
+
+ .EXAMPLE
+ AppMode -Light
+
+ .EXAMPLE
+ AppMode -Dark
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function AppMode
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Light"
+ )]
+ [switch]
+ $Light,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Dark"
+ )]
+ [switch]
+ $Dark
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Light"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -PropertyType DWord -Value 1 -Force
+ }
+ "Dark"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -PropertyType DWord -Value 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "New App Installed" indicator
+ Скрывать/показывать уведомление "Установлено новое приложение"
+
+ .PARAMETER Hide
+ Hide the "New App Installed" indicator
+ Скрывать уведомление "Установлено новое приложение"
+
+ .PARAMETER Show
+ Show the "New App Installed" indicator
+ Показывать уведомление "Установлено новое приложение"
+
+ .EXAMPLE
+ NewAppInstalledNotification -Hide
+
+ .EXAMPLE
+ NewAppInstalledNotification -Show
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function NewAppInstalledNotification
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ 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
+ }
+ "Show"
+ {
+ 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 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide user/show first sign-in animation after the upgrade
+ Скрывать/показывать анимацию при первом входе в систему после обновления
+
+ .PARAMETER Hide
+ Hide user/show first sign-in animation after the upgrade
+ Скрывать/показывать анимацию при первом входе в систему после обновления
+
+ .PARAMETER Show
+ Hide user/show first sign-in animation after the upgrade
+ Скрывать/показывать анимацию при первом входе в систему после обновления
+
+ .EXAMPLE
+ FirstLogonAnimation -Disable
+
+ .EXAMPLE
+ FirstLogonAnimation -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function FirstLogonAnimation
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableFirstLogonAnimation -PropertyType DWord -Value 0 -Force
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableFirstLogonAnimation -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Set the quality factor of the JPEG desktop wallpapers to maximum/default
+ Установить коэффициент качества обоев рабочего стола в формате JPEG на максимальный/по умолчанию
+
+ .PARAMETER Max
+ Set the quality factor of the JPEG desktop wallpapers to maximum
+ Установить коэффициент качества обоев рабочего стола в формате JPEG на максимальный
+
+ .PARAMETER Default
+ Set the quality factor of the JPEG desktop wallpapers to default
+ Установить коэффициент качества обоев рабочего стола в формате JPEG на значение по умолчанию
+
+ .EXAMPLE
+ JPEGWallpapersQuality -Max
+
+ .EXAMPLE
+ JPEGWallpapersQuality -Default
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function JPEGWallpapersQuality
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Max"
+ )]
+ [switch]
+ $Max,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Default"
+ )]
+ [switch]
+ $Default
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Max"
+ {
+ New-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name JPEGImportQuality -PropertyType DWord -Value 100 -Force
+ }
+ "Default"
+ {
+ Remove-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name JPEGImportQuality -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Start Task Manager in the expanded/compact mode
+ Запускать Диспетчера задач в развернутом/свернутом виде
+
+ .PARAMETER Expanded
+ Start Task Manager in the expanded mode
+ Запускать Диспетчера задач в развернутом виде
+
+ .PARAMETER Compact
+ Start Task Manager in the compact mode
+ Запускать Диспетчера задач в свернутом виде
+
+ .EXAMPLE
+ TaskManagerWindow -Expanded
+
+ .EXAMPLE
+ TaskManagerWindow -Compact
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function TaskManagerWindow
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Expanded"
+ )]
+ [switch]
+ $Expanded,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Compact"
+ )]
+ [switch]
+ $Compact
+ )
+
+ $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 -ErrorAction Ignore
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Expanded"
+ {
+ $Preferences.Preferences[28] = 0
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\TaskManager -Name Preferences -PropertyType Binary -Value $Preferences.Preferences -Force
+ }
+ "Compact"
+ {
+ $Preferences.Preferences[28] = 1
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\TaskManager -Name Preferences -PropertyType Binary -Value $Preferences.Preferences -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Show/hide a notification when your PC requires a restart to finish updating
+ Показывать/скрывать уведомление, когда компьютеру требуется перезагрузка для завершения обновления
+
+ .PARAMETER Hide
+ Hide a notification when your PC requires a restart to finish updating
+ Скрывать уведомление, когда компьютеру требуется перезагрузка для завершения обновления
+
+ .PARAMETER Show
+ Show a notification when your PC requires a restart to finish updating
+ Показывать уведомление, когда компьютеру требуется перезагрузка для завершения обновления
+
+ .EXAMPLE
+ RestartNotification -Hide
+
+ .EXAMPLE
+ RestartNotification -Show
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function RestartNotification
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name RestartNotificationsAllowed2 -PropertyType DWord -Value 0 -Force
+ }
+ "Show"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name RestartNotificationsAllowed2 -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Do not add/add the "- Shortcut" suffix to the file name of created shortcuts
+ Нe дoбaвлять/добавлять "- яpлык" к имени coздaвaeмых яpлыков
+
+ .PARAMETER Disable
+ Do not add the "- Shortcut" suffix to the file name of created shortcuts
+ Нe дoбaвлять "- яpлык" к имени coздaвaeмых яpлыков
+
+ .PARAMETER Enable
+ Add the "- Shortcut" suffix to the file name of created shortcuts
+ Добавлять "- яpлык" к имени coздaвaeмых яpлыков
+
+ .EXAMPLE
+ ShortcutsSuffix -Disable
+
+ .EXAMPLE
+ ShortcutsSuffix -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function ShortcutsSuffix
+{
+ 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\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
+ }
+ "Enable"
+ {
+ Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\NamingTemplates -Name ShortcutNameTemplate -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Use/do not use the PrtScn button to open screen snipping
+ Использовать/не использовать кнопку PRINT SCREEN, чтобы запустить функцию создания фрагмента экрана
+
+ .PARAMETER Disable
+ Use the PrtScn button to open screen snipping
+ Использовать кнопку PRINT SCREEN, чтобы запустить функцию создания фрагмента экрана
+
+ .PARAMETER Enable
+ Do not use the PrtScn button to open screen snipping
+ Не использовать кнопку PRINT SCREEN, чтобы запустить функцию создания фрагмента экрана
+
+ .EXAMPLE
+ PrtScnSnippingTool -Disable
+
+ .EXAMPLE
+ PrtScnSnippingTool -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function PrtScnSnippingTool
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path "HKCU:\Control Panel\Keyboard" -Name PrintScreenKeyForSnippingEnabled -PropertyType DWord -Value 0 -Force
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path "HKCU:\Control Panel\Keyboard" -Name PrintScreenKeyForSnippingEnabled -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Let/do not let use a different input method for each app window
+ Позволить/не позволять выбирать метод ввода для каждого окна
+
+ .PARAMETER Disable
+ Let use a different input method for each app window
+ Позволить выбирать метод ввода для каждого окна
+
+ .PARAMETER Enable
+ Do not let use a different input method for each app window
+ Не позволять выбирать метод ввода для каждого окна
+
+ .EXAMPLE
+ AppsLanguageSwitch -Disable
+
+ .EXAMPLE
+ AppsLanguageSwitch -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function AppsLanguageSwitch
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ Set-WinLanguageBarOption -UseLegacySwitchMode
+ }
+ "Enable"
+ {
+ Set-WinLanguageBarOption
+ }
+ }
+}
+#endregion UI & Personalization
+
+#region System
+#region StorageSense
+<#
+ .SYNOPSIS
+ Turn on/turn off Storage Sense
+ Включить/выключить Контроль памяти
+
+ .PARAMETER Disable
+ Turn off Storage Sense
+ Выключить Контроль памяти
+
+ .PARAMETER Enable
+ Turn on off Storage Sense
+ Включить Контроль памяти
+
+ .EXAMPLE
+ StorageSense -Disable
+
+ .EXAMPLE
+ StorageSense -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function StorageSense
+{
+ 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\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 0 -Force
+ }
+ "Enable"
+ {
+ 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
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Run Storage Sense every month/during low free disk space
+ Запускать Контроль памяти каждый месяц/когда остается мало место на диске
+
+ .PARAMETER Disable
+ Run Storage Sense every month/during low free disk space
+ Запускать Контроль памяти каждый месяц/когда остается мало место на диске
+
+ .PARAMETER Enable
+ Run Storage Sense every month/during low free disk space
+ Запускать Контроль памяти каждый месяц/когда остается мало место на диске
+
+ .EXAMPLE
+ StorageSenseFrequency -Month
+
+ .EXAMPLE
+ StorageSenseFrequency -Default
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function StorageSenseFrequency
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Month"
+ )]
+ [switch]
+ $Month,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Default"
+ )]
+ [switch]
+ $Default
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Month"
+ {
+ if ((Get-ItemPropertyValue -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 01) -eq "1")
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 2048 -PropertyType DWord -Value 30 -Force
+ }
+ }
+ "Default"
+ {
+ if ((Get-ItemPropertyValue -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 01) -eq "1")
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 2048 -PropertyType DWord -Value 0 -Force
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Delete/do not delete temporary files that apps aren't using
+ Удалять/не удалять временные файлы, не используемые в приложениях
+
+ .PARAMETER Enable
+ Delete temporary files that apps aren't using
+ Удалять временные файлы, не используемые в приложениях
+
+ .PARAMETER Disable
+ Do not delete temporary files that apps aren't using
+ Не удалять временные файлы, не используемые в приложениях
+
+ .EXAMPLE
+ StorageSenseTempFiles -Enable
+
+ .EXAMPLE
+ StorageSenseTempFiles -Disable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function StorageSenseTempFiles
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ if ((Get-ItemPropertyValue -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 01) -eq "1")
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 04 -PropertyType DWord -Value 1 -Force
+ }
+ }
+ "Disable"
+ {
+ if ((Get-ItemPropertyValue -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 01) -eq "1")
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 04 -PropertyType DWord -Value 0 -Force
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Delete/do not delete files in recycle bin if they have been there for over 30 days
+ Удалять/не удалять файлы из корзины, если они находятся в корзине более 30 дней
+
+ .PARAMETER Disable
+ Delete files in recycle bin if they have been there for over 30 days
+ Удалять файлы из корзины, если они находятся в корзине более 30 дней
+
+ .PARAMETER Enable
+ Do not delete files in recycle bin if they have been there for over 30 days
+ Не удалять файлы из корзины, если они находятся в корзине более 30 дней
+
+ .EXAMPLE
+ StorageSenseRecycleBin -Enable
+
+ .EXAMPLE
+ StorageSenseRecycleBin -Disable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function StorageSenseRecycleBin
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ if ((Get-ItemPropertyValue -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 01) -eq "1")
+ {
+ 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"
+ {
+ if ((Get-ItemPropertyValue -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 01) -eq "1")
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 08 -PropertyType DWord -Value 0 -Force
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy -Name 256 -PropertyType DWord -Value 0 -Force
+ }
+ }
+ }
+}
+#endregion StorageSense
+
+<#
+ .SYNOPSIS
+ Disable (if the device is not a laptop)/enable hibernation
+ Отключить (если устройство не является ноутбуком)/включить режим гибернации
+
+ .PARAMETER Disable
+ Disable hibernation if the device is not a laptop
+ Отключить режим гибернации, если устройство не является ноутбуком
+
+ .PARAMETER Enable
+ Enable hibernation
+ Включить режим гибернации
+
+ .EXAMPLE
+ Hibernate -Enable
+
+ .EXAMPLE
+ Hibernate -Disable
+#>
+function Hibernate
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ POWERCFG /HIBERNATE ON
+ }
+ "Disable"
+ {
+ if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2)
+ {
+ POWERCFG /HIBERNATE OFF
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Change the %TEMP% environment variable path to the "%SystemDrive%\Temp"/default value
+ Изменить путь переменной среды для %TEMP% на "%SystemDrive%\Temp"/по умолчанию
+
+ .PARAMETER SystemDrive
+ Change the %TEMP% environment variable path to "%SystemDrive%\Temp"
+ Изменить путь переменной среды для %TEMP% на "%SystemDrive%\Temp"
+
+ .PARAMETER Default
+ Change the %TEMP% environment variable path to "%LOCALAPPDATA%\Temp"
+ Изменить путь переменной среды для %TEMP% на "%LOCALAPPDATA%\Temp"
+
+ .EXAMPLE
+ TempFolder -SystemDrive
+
+ .EXAMPLE
+ TempFolder -Default
+
+ .NOTES
+ Machine-wide
+ Для всех пользователей
+#>
+function TempFolder
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "SystemDrive"
+ )]
+ [switch]
+ $SystemDrive,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Default"
+ )]
+ [switch]
+ $Default
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "SystemDrive"
+ {
+ # 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
+
+ if (-not (Test-Path -Path $env:SystemDrive\Temp))
+ {
+ New-Item -Path $env:SystemDrive\Temp -ItemType Directory -Force
+ }
+
+ Remove-Item -Path $env:SystemRoot\Temp -Recurse -Force -ErrorAction Ignore
+ Get-Item -Path $env:LOCALAPPDATA\Temp -Force -ErrorAction Ignore | Where-Object -FilterScript {$_.LinkType -ne "SymbolicLink"} | Remove-Item -Recurse -Force -ErrorAction Ignore
+
+ if (Test-Path -Path $env:LOCALAPPDATA\Temp -ErrorAction Ignore)
+ {
+ if ((Get-ChildItem -Path $env:LOCALAPPDATA\Temp -Force -ErrorAction Ignore | Measure-Object).Count -ne 0)
+ {
+ Invoke-Item -Path $env:LOCALAPPDATA\Temp
+
+ do
+ {
+ $Title = ""
+ $Message = $Localization.ClearFolder -f "$env:LOCALAPPDATA\Temp"
+ $Continue = $Localization.Continue
+ $Skip = $Localization.Skip
+ $Options = "&$Continue", "&$Skip"
+ $DefaultChoice = 0
+
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+ switch ($Result)
+ {
+ "0"
+ {
+ # Create a symbolic link to the %SystemDrive%\Temp folder
+ # Создать символическую ссылку к папке %SystemDrive%\Temp
+ try
+ {
+ Get-Item -Path $env:LOCALAPPDATA\Temp -Force | Where-Object -FilterScript {$_.LinkType -ne "SymbolicLink"} | Remove-Item -Recurse -Force -ErrorAction Ignore
+ New-Item -Path $env:LOCALAPPDATA\Temp -ItemType SymbolicLink -Value $env:SystemDrive\Temp -Force -ErrorAction SilentlyContinue
+ }
+ catch [System.Exception]
+ {
+ Write-Verbose -Message $Localization.FilesBlocked -Verbose
+ Write-Verbose -Message ((Get-ChildItem -Path $env:LOCALAPPDATA\Temp -Force).FullName | Out-String) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.SymbolicSkipped -Verbose
+ }
+ }
+ }
+ until (((Get-ChildItem -Path $env:LOCALAPPDATA\Temp -Force -ErrorAction Ignore | Measure-Object).Count -eq 0) -or ($Result -eq 1))
+ }
+ }
+ else
+ {
+ # Create a symbolic link to the %SystemDrive%\Temp folder
+ # Создать символическую ссылку к папке %SystemDrive%\Temp
+ New-Item -Path $env:LOCALAPPDATA\Temp -ItemType SymbolicLink -Value $env:SystemDrive\Temp -Force
+ }
+
+ if (Get-Item -Path $env:LOCALAPPDATA\Temp -ErrorAction Ignore | Where-Object -FilterScript {$_.LinkType -eq "SymbolicLink"})
+ {
+ [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 $env: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 $env:SystemDrive\Temp -Force
+
+ New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name TMP -PropertyType ExpandString -Value $env:SystemDrive\Temp -Force
+ New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name TEMP -PropertyType ExpandString -Value $env:SystemDrive\Temp -Force
+ }
+ }
+ "Default"
+ {
+ # Remove a symbolic link to the %SystemDrive%\Temp folder
+ # Удалить символическую ссылку к папке %SystemDrive%\Temp
+ if (Get-Item -Path $env:LOCALAPPDATA\Temp -Force -ErrorAction Ignore | Where-Object -FilterScript {$_.LinkType -eq "SymbolicLink"})
+ {
+ (Get-Item -Path $env:LOCALAPPDATA\Temp -Force).Delete()
+ }
+
+ if (-not (Test-Path -Path $env:SystemRoot\Temp))
+ {
+ New-Item -Path $env:SystemRoot\Temp -ItemType Directory -Force
+ }
+ if (-not (Test-Path -Path $env:LOCALAPPDATA\Temp))
+ {
+ New-Item -Path $env:LOCALAPPDATA\Temp -ItemType Directory -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
+
+ if ((Get-ChildItem -Path $env:SystemDrive\Temp -Force -ErrorAction Ignore | Measure-Object).Count -eq 0)
+ {
+ Remove-Item -Path $env:SystemDrive\Temp -Recurse -Force
+ }
+ else
+ {
+ Write-Verbose -Message ($Localization.TempNotEmpty -f $env:TEMP) -Verbose
+ }
+
+ [Environment]::SetEnvironmentVariable("TMP", "$env:LOCALAPPDATA\Temp", "User")
+ [Environment]::SetEnvironmentVariable("TMP", "$env:SystemRoot\TEMP", "Machine")
+ [Environment]::SetEnvironmentVariable("TMP", "$env:LOCALAPPDATA\Temp", "Process")
+ New-ItemProperty -Path HKCU:\Environment -Name TMP -PropertyType ExpandString -Value $env:LOCALAPPDATA\Temp -Force
+
+ [Environment]::SetEnvironmentVariable("TEMP", "$env:LOCALAPPDATA\Temp", "User")
+ [Environment]::SetEnvironmentVariable("TEMP", "$env:SystemRoot\TEMP", "Machine")
+ [Environment]::SetEnvironmentVariable("TEMP", "$env:LOCALAPPDATA\Temp", "Process")
+ New-ItemProperty -Path HKCU:\Environment -Name TEMP -PropertyType ExpandString -Value $env:LOCALAPPDATA\Temp -Force
+
+ New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name TMP -PropertyType ExpandString -Value $env:SystemRoot\TEMP -Force
+ New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name TEMP -PropertyType ExpandString -Value $env:SystemRoot\TEMP -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable Windows 260 character path limit
+ Выключить/включить ограничение Windows на 260 символов в пути
+
+ .PARAMETER Disable
+ Disable Windows 260 character path limit
+ Включить ограничение Windows на 260 символов в пути
+
+ .PARAMETER Enable
+ Enable Windows 260 character path limit
+ Включить ограничение Windows на 260 символов в пути
+
+ .EXAMPLE
+ Win32LongPathLimit -Disable
+
+ .EXAMPLE
+ Win32LongPathLimit -Enable
+#>
+function Win32LongPathLimit
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled -PropertyType DWord -Value 1 -Force
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled -PropertyType DWord -Value 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Display/do not dispaly the Stop error information on the BSoD
+ Отображать/не отображать Stop-ошибку при появлении BSoD
+
+ .PARAMETER Disable
+ Disable Windows 260 characters path limit
+ Включить ограничение Windows на 260 символов в пути
+
+ .PARAMETER Enable
+ Enable Windows 260 characters path limit
+ Включить ограничение Windows на 260 символов в пути
+
+ .EXAMPLE
+ BSoDStopError -Disable
+
+ .EXAMPLE
+ BSoDStopError -Enable
+#>
+function BSoDStopError
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\CrashControl -Name DisplayParameters -PropertyType DWord -Value 0 -Force
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\CrashControl -Name DisplayParameters -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Change "Behavior of the elevation prompt for administrators in Admin Approval Mode" to "Elevate without prompting"/"Prompt for consent for non-Windows binaries"
+ Изменить "Поведение запроса на повышение прав для администраторов в режиме одобрения администратором" на "Повышение прав без запроса"/"Запрос согласия для исполняемых файлов, отличных от Windows"
+
+ .PARAMETER Disable
+ Change "Behavior of the elevation prompt for administrators in Admin Approval Mode" to "Elevate without prompting"
+ Изменить "Поведение запроса на повышение прав для администраторов в режиме одобрения администратором" на "Повышение прав без запроса"
+
+ .PARAMETER Enable
+ Change "Behavior of the elevation prompt for administrators in Admin Approval Mode" to "Prompt for consent for non-Windows binaries"
+ Изменить "Поведение запроса на повышение прав для администраторов в режиме одобрения администратором" на "Запрос согласия для исполняемых файлов, отличных от Windows"
+
+ .EXAMPLE
+ AdminApprovalMode -Disable
+
+ .EXAMPLE
+ AdminApprovalMode -Enable
+#>
+function AdminApprovalMode
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -PropertyType DWord -Value 0 -Force
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -PropertyType DWord -Value 5 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Turn on/turn off access to mapped drives from app running with elevated permissions with Admin Approval Mode enabled
+ Включить/выключить доступ к сетевым дискам при включенном режиме одобрения администратором при доступе из программ, запущенных с повышенными правами
+
+ .PARAMETER Disable
+ Turn off access to mapped drives from app running with elevated permissions with Admin Approval Mode enabled
+ Выключить доступ к сетевым дискам при включенном режиме одобрения администратором при доступе из программ, запущенных с повышенными правами
+
+ .PARAMETER Enable
+ Turn on access to mapped drives from app running with elevated permissions with Admin Approval Mode enabled
+ Включить доступ к сетевым дискам при включенном режиме одобрения администратором при доступе из программ, запущенных с повышенными правами
+
+ .EXAMPLE
+ MappedDrivesAppElevatedAccess -Disable
+
+ .EXAMPLE
+ MappedDrivesAppElevatedAccess -Enable
+#>
+function MappedDrivesAppElevatedAccess
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLinkedConnections -PropertyType DWord -Value 0 -Force
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLinkedConnections -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Opt-out of/opt-in to the Delivery Optimization-assisted updates downloading
+ Выключить/включить загрузку обновлений с помощью оптимизации доставки
+
+ .PARAMETER Disable
+ Opt-out of to the Delivery Optimization-assisted updates downloading
+ Отказаться от загрузки обновлений с помощью оптимизации доставки
+
+ .PARAMETER Enable
+ Opt-in to the Delivery Optimization-assisted updates downloading
+ Включить загрузку обновлений с помощью оптимизации доставки
+
+ .EXAMPLE
+ DeliveryOptimization -Disable
+
+ .EXAMPLE
+ DeliveryOptimization -Enable
+#>
+function DeliveryOptimization
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path Registry::HKEY_USERS\S-1-5-20\SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Settings -Name DownloadMode -PropertyType DWord -Value 0 -Force
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path Registry::HKEY_USERS\S-1-5-20\SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Settings -Name DownloadMode -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Always/never wait for the network at computer startup and logon for workgroup networks
+ Всегда/никогда не ждать сеть при запуске и входе в систему для рабочих групп
+
+ .PARAMETER Disable
+ Never wait for the network at computer startup and logon for workgroup networks
+ Никогда не ждать сеть при запуске и входе в систему для рабочих групп
+
+ .PARAMETER Enable
+ Always wait for the network at computer startup and logon for workgroup networks
+ Всегда ждать сеть при запуске и входе в систему для рабочих групп
+
+ .EXAMPLE
+ WaitNetworkStartup -Disable
+
+ .EXAMPLE
+ WaitNetworkStartup -Enable
+#>
+function WaitNetworkStartup
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ if ((Get-CimInstance -ClassName CIM_ComputerSystem).PartOfDomain -eq $true)
+ {
+ Remove-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name SyncForegroundPolicy -Force -ErrorAction SilentlyContinue
+ }
+ }
+ "Enable"
+ {
+ 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
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Do not let/let Windows decide which printer should be the default one
+ Не разрешать/разрешать Windows решать, какой принтер должен использоваться по умолчанию
+
+ .PARAMETER Disable
+ Do not let Windows decide which printer should be the default one
+ Не разрешать Windows решать, какой принтер должен использоваться по умолчанию
+
+ .PARAMETER Enable
+ Let Windows decide which printer should be the default one
+ Разрешать Windows решать, какой принтер должен использоваться по умолчанию
+
+ .EXAMPLE
+ WindowsManageDefaultPrinter -Disable
+
+ .EXAMPLE
+ WindowsManageDefaultPrinter -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function WindowsManageDefaultPrinter
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name LegacyDefaultPrinterMode -PropertyType DWord -Value 1 -Force
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name LegacyDefaultPrinterMode -PropertyType DWord -Value 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable Windows features
+ Отключить/включить компоненты Windows
+
+ .PARAMETER Disable
+ Disable Windows features
+ Отключить компоненты Windows
+
+ .PARAMETER Enable
+ Enable Windows features
+ Включить компоненты Windows
+
+ .EXAMPLE
+ WindowsFeatures -Disable
+
+ .EXAMPLE
+ WindowsFeatures -Enable
+
+ .NOTES
+ A pop-up dialog box enables the user to select features to remove
+ Current user only
+
+ Используется всплывающее диалоговое окно, позволяющее пользователю отметить компоненты на удаление
+ Только для текущего пользователя
+#>
+function WindowsFeatures
+{
+ 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 Windows Features items to remove
+ # Создать массив имен компонентов Windows для удаления
+ $Features = New-Object -TypeName System.Collections.ArrayList($null)
+
+ # The following Windows Features are recommended the user to remove
+ # Следующие компоненты Windows рекомендуются к удалению
+ $WindowsFeatures = @(
+ # 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"
+ )
+ #endregion Variables
+
+ #region XAML Markup
+ # The section defines the design of the upcoming dialog box
+ # Раздел, определяющий форму диалогового окна
+ [xml]$XAML = '
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ '
+ #endregion XAML Markup
+
+ $Reader = (New-Object -TypeName System.Xml.XmlNodeReader -ArgumentList $XAML)
+ $Form = [Windows.Markup.XamlReader]::Load($Reader)
+ $XAML.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | ForEach-Object -Process {
+ Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name) -Scope Global
+ }
+
+ #region Functions
+ function Get-CheckboxClicked
+ {
+ [CmdletBinding()]
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ValueFromPipeline = $true
+ )]
+ [ValidateNotNull()]
+ $CheckBox
+ )
+
+ $Feature = $CheckBox.Parent.Children[1].Text
+ if ($CheckBox.IsChecked)
+ {
+ [void]$Features.Add($Feature)
+ }
+ else
+ {
+ [void]$Features.Remove($Feature)
+ }
+ if ($Features.Count -gt 0)
+ {
+ $Button.IsEnabled = $true
+ }
+ else
+ {
+ $Button.IsEnabled = $false
+ }
+ }
+
+ function DisableButton
+ {
+ [void]$Window.Close()
+ Disable-WindowsOptionalFeature -Online -FeatureName $Features -NoRestart
+ }
+
+ function EnableButton
+ {
+ [void]$Window.Close()
+ Enable-WindowsOptionalFeature -Online -FeatureName $Features -NoRestart
+ }
+
+ function Add-FeatureControl
+ {
+ [CmdletBinding()]
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ValueFromPipeline = $true
+ )]
+ [ValidateNotNull()]
+ [string]
+ $Feature
+ )
+
+ $CheckBox = New-Object -TypeName System.Windows.Controls.CheckBox
+ $CheckBox.Add_Click({Get-CheckboxClicked -CheckBox $_.Source})
+
+ $TextBlock = New-Object -TypeName System.Windows.Controls.TextBlock
+ $TextBlock.Text = $Feature
+
+ $StackPanel = New-Object -TypeName System.Windows.Controls.StackPanel
+ [void]$StackPanel.Children.Add($CheckBox)
+ [void]$StackPanel.Children.Add($TextBlock)
+
+ [void]$PanelContainer.Children.Add($StackPanel)
+
+ $CheckBox.IsChecked = $false
+
+ # If feature checked, add to the array list to remove
+ # Если компонент выделен, то добавить в массив для удаления
+ if ($WindowsFeatures | Where-Object -FilterScript {$Feature -like $_})
+ {
+ $CheckBox.IsChecked = $true
+ [void]$Features.Add($Feature)
+ }
+ }
+ #endregion Functions
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ #region Events Handlers
+ $OptionalFeatures = New-Object -TypeName System.Collections.ArrayList($null)
+ # Window Loaded Event
+ $Window.Add_Loaded({
+ $OFS = "|"
+ $OptionalFeatures = Get-WindowsOptionalFeature -Online | Where-Object -FilterScript {($_.State -eq "Disabled" -or $_.State -eq "DisablePending") -and ($_.FeatureName -in $WindowsFeatures)}
+ if ($OptionalFeatures.Count -gt 0)
+ {
+ $OptionalFeatures | ForEach-Object -Process {
+ Add-FeatureControl -Feature $_.FeatureName
+ }
+
+ $Button.Content = $Localization.Enable
+ }
+ else
+ {
+ Write-Verbose -Message $Localization.NoData -Verbose
+ $Form.Close()
+ }
+ $OFS = " "
+ })
+
+ # Button Click Event
+ $Button.Add_Click({EnableButton})
+ #endregion Events Handlers
+ }
+ "Disable"
+ {
+ #region Events Handlers
+ $OptionalFeatures = New-Object -TypeName System.Collections.ArrayList($null)
+ # Window Loaded Event
+ $Window.Add_Loaded({
+ $OFS = "|"
+ $OptionalFeatures = Get-WindowsOptionalFeature -Online | Where-Object -FilterScript {($_.State -eq "Enabled" -or $_.State -eq "EnablePending") -and ($_.FeatureName -in $WindowsFeatures)}
+ if ($OptionalFeatures.Count -gt 0)
+ {
+ $OptionalFeatures | ForEach-Object -Process {
+ Add-FeatureControl -Feature $_.FeatureName
+ }
+
+ $Button.Content = $Localization.Disable
+ }
+ else
+ {
+ Write-Verbose -Message $Localization.NoData -Verbose
+ $Form.Close()
+ }
+ $OFS = " "
+ })
+
+ # Button Click Event
+ $Button.Add_Click({DisableButton})
+ #endregion Events Handlers
+ }
+ }
+
+ Write-Verbose -Message $Localization.DialogBoxOpening -Verbose
+
+ $Window.Title = $Localization.WindowsFeaturesWindowTitle
+ $Form.ShowDialog() | Out-Null
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable Features On Demand v2 (FODv2) capabilities
+ Отключить/включить компоненты "Функции по требованию" (FODv2)
+
+ .PARAMETER Disable
+ Disable Features On Demand v2 (FODv2) capabilities
+ Отключить компоненты "Функции по требованию" (FODv2)
+
+ .PARAMETER Enable
+ Enable Features On Demand v2 (FODv2) capabilities
+ Включить компоненты "Функции по требованию" (FODv2)
+
+ .EXAMPLE
+ WindowsCapabilities -Disable
+
+ .EXAMPLE
+ WindowsCapabilities -Enable
+
+ .NOTES
+ A pop-up dialog box enables the user to select features to remove
+ Current user only
+
+ Используется всплывающее диалоговое окно, позволяющее пользователю отметить компоненты на удаление
+ Только для текущего пользователя
+#>
+function WindowsCapabilities
+{
+ 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 FODv2 items to disable
+ # Создать массив имен дополнительных компонентов для отключения
+ $Capabilities = New-Object -TypeName System.Collections.ArrayList($null)
+
+ # The following FODv2 items will have their checkboxes checked
+ # Следующие дополнительные компоненты будут иметь чекбоксы отмеченными
+ $CheckedCapabilities = @(
+ # Steps Recorder
+ # Средство записи действий
+ "App.StepsRecorder*",
+
+ # Microsoft Quick Assist
+ # Быстрая поддержка (Майкрософт)
+ "App.Support.QuickAssist*",
+
+ # Windows Media Player
+ # Проигрыватель Windows Media
+ "Media.WindowsMediaPlayer*",
+
+ # Integrated faxing and scanning application for Windows
+ # Факсы и сканирование Windows
+ "Print.Fax.Scan*"
+ )
+
+ # The following FODv2 items will be excluded from the display
+ # Следующие дополнительные компоненты будут исключены из отображения
+ $ExcludedCapabilities = @(
+ # The DirectX Database to configure and optimize apps when multiple Graphics Adapters are present
+ # База данных DirectX для настройки и оптимизации приложений при наличии нескольких графических адаптеров
+ "DirectX\.Configuration\.Database",
+
+ # Language components
+ # Языковые компоненты
+ "Language\.",
+
+ # Mail, contacts, and calendar sync component
+ # Компонент синхронизации почты, контактов и календаря
+ "OneCoreUAP\.OneSync"
+ )
+ #endregion Variables
+
+ #region XAML Markup
+ # The section defines the design of the upcoming dialog box
+ # Раздел, определяющий форму диалогового окна
+ [xml]$XAML = '
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ '
+ #endregion XAML Markup
+
+ $Reader = (New-Object -TypeName System.Xml.XmlNodeReader -ArgumentList $XAML)
+ $Form = [Windows.Markup.XamlReader]::Load($Reader)
+ $XAML.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | ForEach-Object -Process {
+ Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name) -Scope Global
+ }
+
+ #region Functions
+ function Get-CheckboxClicked
+ {
+ [CmdletBinding()]
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ValueFromPipeline = $true
+ )]
+ [ValidateNotNull()]
+ $CheckBox
+ )
+
+ $Capability = $CheckBox.Parent.Children[1].Text
+ if ($CheckBox.IsChecked)
+ {
+ [void]$Capabilities.Add($Capability)
+ }
+ else
+ {
+ [void]$Capabilities.Remove($Capability)
+ }
+ if ($Capabilities.Count -gt 0)
+ {
+ $Button.IsEnabled = $true
+ }
+ else
+ {
+ $Button.IsEnabled = $false
+ }
+ }
+
+ function DisableButton
+ {
+ [void]$Window.Close()
+ $OFS = "|"
+ Get-WindowsCapability -Online | Where-Object -FilterScript {$_.Name -cmatch $Capabilities} | Remove-WindowsCapability -Online
+ $OFS = " "
+ }
+
+ function EnableButton
+ {
+ Write-Verbose -Message $Localization.Patient -Verbose
+
+ [void]$Window.Close()
+ $OFS = "|"
+ Get-WindowsCapability -Online | Where-Object -FilterScript {$_.Name -cmatch $Capabilities} | Add-WindowsCapability -Online
+ $OFS = " "
+ }
+
+ function Add-CapabilityControl
+ {
+ [CmdletBinding()]
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ValueFromPipeline = $true
+ )]
+ [ValidateNotNull()]
+ [string]
+ $Capability
+ )
+
+ $CheckBox = New-Object -TypeName System.Windows.Controls.CheckBox
+ $CheckBox.Add_Click({Get-CheckboxClicked -CheckBox $_.Source})
+
+ $TextBlock = New-Object -TypeName System.Windows.Controls.TextBlock
+ $TextBlock.Text = $Capability
+
+ $StackPanel = New-Object -TypeName System.Windows.Controls.StackPanel
+ [void]$StackPanel.Children.Add($CheckBox)
+ [void]$StackPanel.Children.Add($TextBlock)
+
+ [void]$PanelContainer.Children.Add($StackPanel)
+
+ $CheckBox.IsChecked = $false
+
+ # If capability checked, add to the array list to remove
+ # Если компонент выделен, то добавить в массив для удаления
+ if ($CheckedCapabilities | Where-Object -FilterScript {$Capability -like $_})
+ {
+ $CheckBox.IsChecked = $true
+ [void]$Capabilities.Add($Capability)
+ }
+ }
+ #endregion Functions
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ #region Events Handlers
+ $OptionalCapabilities = New-Object -TypeName System.Collections.ArrayList($null)
+ # Window Loaded Event
+ $Window.Add_Loaded({
+ $OFS = "|"
+ $OptionalCapabilities = Get-WindowsCapability -Online | Where-Object -FilterScript {($_.State -eq "NotPresent") -and ($_.Name -cmatch $CheckedCapabilities) -and ($_.Name -cnotmatch $ExcludedCapabilities)}
+ if ($OptionalCapabilities.Count -gt 0)
+ {
+ $OptionalCapabilities | ForEach-Object -Process {
+ Add-CapabilityControl -Capability $_.Name
+ }
+
+ $Button.Content = $Localization.Enable
+ }
+ else
+ {
+ Write-Verbose -Message $Localization.NoData -Verbose
+ $Form.Close()
+ }
+ $OFS = " "
+ })
+
+ # Button Click Event
+ $Button.Add_Click({EnableButton})
+ #endregion Events Handlers
+ }
+ "Disable"
+ {
+ #region Events Handlers
+ $OptionalCapabilities = New-Object -TypeName System.Collections.ArrayList($null)
+ # Window Loaded Event
+ $Window.Add_Loaded({
+ $OFS = "|"
+ $OptionalCapabilities = Get-WindowsCapability -Online | Where-Object -FilterScript {($_.State -eq "Installed") -and ($_.Name -cmatch $CheckedCapabilities) -and ($_.Name -cnotmatch $ExcludedCapabilities)}
+ if ($OptionalCapabilities.Count -gt 0)
+ {
+ $OptionalCapabilities | ForEach-Object -Process {
+ Add-CapabilityControl -Capability $_.Name
+ }
+
+ $Button.Content = $Localization.Disable
+ }
+ else
+ {
+ Write-Verbose -Message $Localization.NoData -Verbose
+ $Form.Close()
+ }
+ $OFS = " "
+ })
+
+ # Button Click Event
+ $Button.Add_Click({DisableButton})
+ #endregion Events Handlers
+ }
+ }
+
+ try
+ {
+ (Invoke-WebRequest -Uri https://www.google.com -UseBasicParsing -DisableKeepAlive -Method Head).StatusDescription
+ }
+ catch [System.Net.WebException]
+ {
+ Write-Warning -Message $Localization.NoInternetConnection
+ Write-Error -Message $Localization.NoInternetConnection -ErrorAction SilentlyContinue
+ return
+ }
+
+ Write-Verbose -Message $Localization.DialogBoxOpening -Verbose
+
+ $Window.Title = $Localization.FODWindowTitle
+ $Form.ShowDialog() | Out-Null
+}
+
+<#
+ .SYNOPSIS
+ Opt-in to/opt-out of Microsoft Update service, so to receive updates for other Microsoft products
+ Подключаться/не подключаться к службе Microsoft Update так, чтобы при обновлении Windows получать обновления для других продуктов Майкрософт
+
+ .PARAMETER Disable
+ Opt-out of Microsoft Update service, so to receive updates for other Microsoft products
+ Не подключаться к службе Microsoft Update так, чтобы при обновлении Windows получать обновления для других продуктов Майкрософт
+
+ .PARAMETER Enable
+ Opt-in to Microsoft Update service, so to receive updates for other Microsoft products
+ Подключаться к службе Microsoft Update так, чтобы при обновлении Windows получать обновления для других продуктов Майкрософт
+
+ .EXAMPLE
+ UpdateMicrosoftProducts -Disable
+
+ .EXAMPLE
+ UpdateMicrosoftProducts -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function UpdateMicrosoftProducts
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ if ((New-Object -ComObject Microsoft.Update.ServiceManager).Services | Where-Object {$_.ServiceID -eq "7971f918-a847-4430-9279-4a52d1efe18d"} )
+ {
+ (New-Object -ComObject Microsoft.Update.ServiceManager).RemoveService("7971f918-a847-4430-9279-4a52d1efe18d")
+ }
+ }
+ "Enable"
+ {
+ (New-Object -ComObject Microsoft.Update.ServiceManager).AddService2("7971f918-a847-4430-9279-4a52d1efe18d", 7, "")
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Set the power management scheme on "High performance" (if device is a desktop)/"Balanced"
+ Установить схему управления питанием на "Высокая производительность" (если устройство является стационарным ПК)/"Сбалансированная"
+
+ .PARAMETER High
+ Set the power management scheme on "High performance" if device is a desktop
+ Установить схему управления питанием на "Высокая производительность"
+
+ .PARAMETER Balanced
+ Set the power management scheme on "Balanced"
+ Установить схему управления питанием на Сбалансированная"
+
+ .EXAMPLE
+ PowerManagementScheme -High
+
+ .EXAMPLE
+ PowerManagementScheme -Balanced
+#>
+function PowerManagementScheme
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "High"
+ )]
+ [switch]
+ $High,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Balanced"
+ )]
+ [switch]
+ $Balanced
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "High"
+ {
+ if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -eq 1)
+ {
+ POWERCFG /SETACTIVE SCHEME_MIN
+ }
+ }
+ "Balanced"
+ {
+ POWERCFG /SETACTIVE SCHEME_BALANCED
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Use/do not use latest installed .NET runtime for all apps
+ Использовать/не использовать последнюю установленную среду выполнения .NET для всех приложений
+
+ .PARAMETER Disable
+ Do not use latest installed .NET runtime for all apps
+ Не использовать последнюю установленную среду выполнения .NET для всех приложений
+
+ .PARAMETER Enable
+ Use use latest installed .NET runtime for all apps
+ Использовать последнюю установленную среду выполнения .NET для всех приложений
+
+ .EXAMPLE
+ LatestInstalled.NET -Disable
+
+ .EXAMPLE
+ LatestInstalled.NET -Enable
+#>
+function LatestInstalled.NET
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\.NETFramework -Name OnlyUseLatestCLR -Force -ErrorAction SilentlyContinue
+ Remove-ItemProperty -Path HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework -Name OnlyUseLatestCLR -Force -ErrorAction SilentlyContinue
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\.NETFramework -Name OnlyUseLatestCLR -PropertyType DWord -Value 1 -Force
+ New-ItemProperty -Path HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework -Name OnlyUseLatestCLR -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Do not allow/allow the computer (if device is not a laptop) to turn off the network adapters to save power
+ Запретить/разрешить отключение всех сетевых адаптеров для экономии энергии (если устройство не является ноутбуком)
+
+ .PARAMETER Disable
+ Do not allow the computer (if device is not a laptop) to turn off the network adapters to save power
+ Запретить отключение всех сетевых адаптеров для экономии энергии (если устройство не является ноутбуком)
+
+ .PARAMETER Enable
+ Allow the computer (if device is not a laptop) to turn off the network adapters to save power
+ Разрешить отключение всех сетевых адаптеров для экономии энергии (если устройство не является ноутбуком)
+
+ .EXAMPLE
+ PCTurnOffDevice -Disable
+
+ .EXAMPLE
+ PCTurnOffDevice -Enable
+#>
+function PCTurnOffDevice
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ $Adapters = Get-NetAdapter -Physical | Get-NetAdapterPowerManagement | Where-Object -FilterScript {$_.AllowComputerToTurnOffDevice -ne "Unsupported"}
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2)
+ {
+ foreach ($Adapter in $Adapters)
+ {
+ $Adapter.AllowComputerToTurnOffDevice = "Disabled"
+ $Adapter | Set-NetAdapterPowerManagement
+ }
+ }
+ }
+ "Enable"
+ {
+ if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2)
+ {
+ foreach ($Adapter in $Adapters)
+ {
+ $Adapter.AllowComputerToTurnOffDevice = "Enabled"
+ $Adapter | Set-NetAdapterPowerManagement
+ }
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Set/reset the default input method to the English language
+ Установить/сбросить метод ввода по умолчанию на английский язык
+
+ .PARAMETER English
+ Set the default input method to the English language
+ Установить метод ввода по умолчанию на английский язык
+
+ .PARAMETER Default
+ Reset the default input method to the English language
+ Сбросить метод ввода по умолчанию на английский язык
+
+ .EXAMPLE
+ SetInputMethod -English
+
+ .EXAMPLE
+ SetInputMethod -Default
+#>
+function SetInputMethod
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "English"
+ )]
+ [switch]
+ $English,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Default"
+ )]
+ [switch]
+ $Default
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "English"
+ {
+ Set-WinDefaultInputMethodOverride -InputTip "0409:00000409"
+ }
+ "Default"
+ {
+ Remove-ItemProperty -Path "HKCU:\Control Panel\International\User Profile" -Name InputMethodOverride -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Change the location of the user folders to any disks root of your choice using the interactive menu
+ Изменить расположение пользовательских папок в корень любого диска на выбор с помощью интерактивного меню
+
+ .PARAMETER Root
+ Change the location of the user folders to any disks root of your choice using the interactive menu
+ Изменить расположение пользовательских папок в корень любого диска на выбор с помощью интерактивного меню
+
+ .PARAMETER Custom
+ Select a folder for the location of the user folders manually using a folder browser dialog
+ Выбрать папку для расположения пользовательских папок вручную, используя диалог "Обзор папок"
+
+ .PARAMETER Default
+ Change the location of the user folders to the default values
+ Изменить расположение пользовательских папок на значения по умолчанию
+
+ .EXAMPLE
+ SetUserShellFolderLocation -Root
+
+ .EXAMPLE
+ SetUserShellFolderLocation -Custom
+
+ .EXAMPLE
+ SetUserShellFolderLocation -Default
+
+ .NOTES
+ User files or folders won't me moved to a new location
+ Current user only
+
+ Пользовательские файлы и папки не будут перемещены в новое расположение
+ Только для текущего пользователя
+#>
+function SetUserShellFolderLocation
+{
+
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Root"
+ )]
+ [switch]
+ $Root,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Custom"
+ )]
+ [switch]
+ $Custom,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Default"
+ )]
+ [switch]
+ $Default
+ )
+
+ function UserShellFolder
+ {
+ <#
+ .SYNOPSIS
+ Change the location of the each user folder using SHSetKnownFolderPath function
+ Изменить расположение каждой пользовательской папки, используя функцию "SHSetKnownFolderPath"
+ https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath
+
+ .PARAMETER RemoveDesktopINI
+ The RemoveDesktopINI argument removes desktop.ini in the old user shell folder
+ Аргумент "RemoveDesktopINI" удаляет файл desktop.ini из старой пользовательской папки
+
+ .EXAMPLE
+ UserShellFolder -UserFolder Desktop -FolderPath "$env:SystemDrive:\Desktop" -RemoveDesktopINI
+
+ .NOTES
+ User files or folders won't me moved to a new location
+ Пользовательские файлы не будут перенесены в новое расположение
+ #>
+ [CmdletBinding()]
+ param
+ (
+ [Parameter(Mandatory = $true)]
+ [ValidateSet("Desktop", "Documents", "Downloads", "Music", "Pictures", "Videos")]
+ [string]
+ $UserFolder,
+
+ [Parameter(Mandatory = $true)]
+ [string]
+ $FolderPath,
+
+ [Parameter(Mandatory = $false)]
+ [switch]
+ $RemoveDesktopINI
+ )
+
+ function KnownFolderPath
+ {
+ <#
+ .SYNOPSIS
+ Redirect user folders to a new location
+
+ .EXAMPLE
+ KnownFolderPath -KnownFolder Desktop -Path "$env:SystemDrive:\Desktop"
+ #>
+ [CmdletBinding()]
+ param
+ (
+ [Parameter(Mandatory = $true)]
+ [ValidateSet("Desktop", "Documents", "Downloads", "Music", "Pictures", "Videos")]
+ [string]
+ $KnownFolder,
+
+ [Parameter(Mandatory = $true)]
+ [string]
+ $Path
+ )
+
+ $KnownFolders = @{
+ "Desktop" = @("B4BFCC3A-DB2C-424C-B029-7FE99A87C641");
+ "Documents" = @("FDD39AD0-238F-46AF-ADB4-6C85480369C7", "f42ee2d3-909f-4907-8871-4c22fc0bf756");
+ "Downloads" = @("374DE290-123F-4565-9164-39C4925E467B", "7d83ee9b-2244-4e70-b1f5-5393042af1e4");
+ "Music" = @("4BD8D571-6D19-48D3-BE97-422220080E43", "a0c69a99-21c8-4671-8703-7934162fcf1d");
+ "Pictures" = @("33E28130-4E1E-4676-835A-98395C3BC3BB", "0ddd015d-b06c-45d5-8c4c-f59713854639");
+ "Videos" = @("18989B1D-99B5-455B-841C-AB7C74E4DDFC", "35286a68-3c57-41a1-bbb1-0eae73d76c95");
+ }
+
+ $Signature = @{
+ Namespace = "WinAPI"
+ Name = "KnownFolders"
+ Language = "CSharp"
+ MemberDefinition = @"
+[DllImport("shell32.dll")]
+public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, IntPtr token, [MarshalAs(UnmanagedType.LPWStr)] string path);
+"@
+ }
+ if (-not ("WinAPI.KnownFolders" -as [type]))
+ {
+ Add-Type @Signature
+ }
+
+ foreach ($guid in $KnownFolders[$KnownFolder])
+ {
+ [WinAPI.KnownFolders]::SHSetKnownFolderPath([ref]$guid, 0, 0, $Path)
+ }
+ (Get-Item -Path $Path -Force).Attributes = "ReadOnly"
+ }
+
+ $UserShellFoldersRegName = @{
+ "Desktop" = "Desktop"
+ "Documents" = "Personal"
+ "Downloads" = "{374DE290-123F-4565-9164-39C4925E467B}"
+ "Music" = "My Music"
+ "Pictures" = "My Pictures"
+ "Videos" = "My Video"
+ }
+
+ $UserShellFoldersGUID = @{
+ "Desktop" = "{754AC886-DF64-4CBA-86B5-F7FBF4FBCEF5}"
+ "Documents" = "{F42EE2D3-909F-4907-8871-4C22FC0BF756}"
+ "Downloads" = "{7D83EE9B-2244-4E70-B1F5-5393042AF1E4}"
+ "Music" = "{A0C69A99-21C8-4671-8703-7934162FCF1D}"
+ "Pictures" = "{0DDD015D-B06C-45D5-8C4C-F59713854639}"
+ "Videos" = "{35286A68-3C57-41A1-BBB1-0EAE73D76C95}"
+ }
+
+ # Contents of the hidden desktop.ini file for each type of user folders
+ # Содержимое скрытого файла desktop.ini для каждого типа пользовательских папок
+ $DesktopINI = @{
+ "Desktop" = "",
+ "[.ShellClassInfo]",
+ "LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21769",
+ "IconResource=%SystemRoot%\system32\imageres.dll,-183"
+ "Documents" = "",
+ "[.ShellClassInfo]",
+ "LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21770",
+ "IconResource=%SystemRoot%\system32\imageres.dll,-112",
+ "IconFile=%SystemRoot%\system32\shell32.dll",
+ "IconIndex=-235"
+ "Downloads" = "",
+ "[.ShellClassInfo]","LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21798",
+ "IconResource=%SystemRoot%\system32\imageres.dll,-184"
+ "Music" = "",
+ "[.ShellClassInfo]","LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21790",
+ "InfoTip=@%SystemRoot%\system32\shell32.dll,-12689",
+ "IconResource=%SystemRoot%\system32\imageres.dll,-108",
+ "IconFile=%SystemRoot%\system32\shell32.dll","IconIndex=-237"
+ "Pictures" = "",
+ "[.ShellClassInfo]",
+ "LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21779",
+ "InfoTip=@%SystemRoot%\system32\shell32.dll,-12688",
+ "IconResource=%SystemRoot%\system32\imageres.dll,-113",
+ "IconFile=%SystemRoot%\system32\shell32.dll",
+ "IconIndex=-236"
+ "Videos" = "",
+ "[.ShellClassInfo]",
+ "LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21791",
+ "InfoTip=@%SystemRoot%\system32\shell32.dll,-12690",
+ "IconResource=%SystemRoot%\system32\imageres.dll,-189",
+ "IconFile=%SystemRoot%\system32\shell32.dll","IconIndex=-238"
+ }
+
+ # Determining the current user folder path
+ # Определяем текущее значение пути пользовательской папки
+ $UserShellFolderRegValue = Get-ItemPropertyValue -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name $UserShellFoldersRegName[$UserFolder]
+ if ($UserShellFolderRegValue -ne $FolderPath)
+ {
+ if ((Get-ChildItem -Path $UserShellFolderRegValue | Measure-Object).Count -ne 0)
+ {
+ Write-Error -Message ($Localization.UserShellFolderNotEmpty -f $UserShellFolderRegValue) -ErrorAction SilentlyContinue
+ }
+
+ # Creating a new folder if there is no one
+ # Создаем новую папку, если таковая отсутствует
+ if (-not (Test-Path -Path $FolderPath))
+ {
+ New-Item -Path $FolderPath -ItemType Directory -Force
+ }
+
+ # Removing old desktop.ini
+ # Удаляем старый desktop.ini
+ if ($RemoveDesktopINI.IsPresent)
+ {
+ Remove-Item -Path "$UserShellFolderRegValue\desktop.ini" -Force
+ }
+
+ KnownFolderPath -KnownFolder $UserFolder -Path $FolderPath
+ New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name $UserShellFoldersGUID[$UserFolder] -PropertyType ExpandString -Value $FolderPath -Force
+
+ Set-Content -Path "$FolderPath\desktop.ini" -Value $DesktopINI[$UserFolder] -Encoding Unicode -Force
+ (Get-Item -Path "$FolderPath\desktop.ini" -Force).Attributes = "Hidden", "System", "Archive"
+ (Get-Item -Path "$FolderPath\desktop.ini" -Force).Refresh()
+ }
+ }
+
+ <#
+ .SYNOPSIS
+ The "Show menu" function using PowerShell with the up/down arrow keys and enter key to make a selection
+ Функция "Show menu" для перемещения с помощью стрелочек между объектами и Enter для выбора
+
+ .EXAMPLE
+ ShowMenu -Menu $ListOfItems -Default $DefaultChoice
+
+ .NOTES
+ Не работает в PowerShell ISE
+ Doesn't work in PowerShell ISE
+ #>
+ function ShowMenu
+ {
+ [CmdletBinding()]
+ param
+ (
+ [Parameter()]
+ [string]
+ $Title,
+
+ [Parameter(Mandatory = $true)]
+ [array]
+ $Menu,
+
+ [Parameter(Mandatory = $true)]
+ [int]
+ $Default
+ )
+
+ Write-Information -MessageData $Title -InformationAction Continue
+
+ $minY = [Console]::CursorTop
+ $y = [Math]::Max([Math]::Min($Default, $Menu.Count), 0)
+ do
+ {
+ [Console]::CursorTop = $minY
+ [Console]::CursorLeft = 0
+ $i = 0
+ foreach ($item in $Menu)
+ {
+ if ($i -ne $y)
+ {
+ Write-Information -MessageData (' {0}. {1} ' -f ($i+1), $item) -InformationAction Continue
+ }
+ else
+ {
+ Write-Information -MessageData ('[ {0}. {1} ]' -f ($i+1), $item) -InformationAction Continue
+ }
+ $i++
+ }
+
+ $k = [Console]::ReadKey()
+ switch ($k.Key)
+ {
+ "UpArrow"
+ {
+ if ($y -gt 0)
+ {
+ $y--
+ }
+ }
+ "DownArrow"
+ {
+ if ($y -lt ($Menu.Count - 1))
+ {
+ $y++
+ }
+ }
+ "Enter"
+ {
+ return $Menu[$y]
+ }
+ }
+ }
+ while ($k.Key -notin ([ConsoleKey]::Escape, [ConsoleKey]::Enter))
+ }
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Root"
+ {
+ # Store all drives letters to use them within ShowMenu function
+ # Сохранить все буквы диска, чтобы использовать их в функции ShowMenu
+ Write-Verbose -Message $Localization.RetrievingDrivesList -Verbose
+ $DriveLetters = @((Get-Disk | Where-Object -FilterScript {$_.BusType -ne "USB"} | Get-Partition | Get-Volume | Where-Object -FilterScript {$null -ne $_.DriveLetter}).DriveLetter | Sort-Object)
+
+ # If the number of disks is more than one, set the second drive in the list as default drive
+ # Если количество дисков больше одного, сделать второй диск в списке диском по умолчанию
+ if ($DriveLetters.Count -gt 1)
+ {
+ $Global:Default = 1
+ }
+ else
+ {
+ $Global:Default = 0
+ }
+
+ # Desktop
+ # Рабочий стол
+ Write-Verbose -Message $Localization.DesktopDriveSelect -Verbose
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.DesktopRequest
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ $SelectedDrive = ShowMenu -Title $Localization.DesktopDriveSelect -Menu $DriveLetters -Default $Global:Default
+ UserShellFolder -UserFolder Desktop -FolderPath "${SelectedDrive}:\Desktop" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Documents
+ # Документы
+ Write-Verbose -Message $Localization.DocumentsDriveSelect -Verbose
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.DocumentsRequest
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ $SelectedDrive = ShowMenu -Title $Localization.DocumentsDriveSelect -Menu $DriveLetters -Default $Global:Default
+ UserShellFolder -UserFolder Documents -FolderPath "${SelectedDrive}:\Documents" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Downloads
+ # Загрузки
+ Write-Verbose -Message $Localization.DownloadsDriveSelect -Verbose
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.DownloadsRequest
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ $SelectedDrive = ShowMenu -Title $Localization.DownloadsDriveSelect -Menu $DriveLetters -Default $Global:Default
+ UserShellFolder -UserFolder Downloads -FolderPath "${SelectedDrive}:\Downloads" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Music
+ # Музыка
+ Write-Verbose -Message $Localization.MusicDriveSelect -Verbose
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.MusicRequest
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ $SelectedDrive = ShowMenu -Title $Localization.MusicDriveSelect -Menu $DriveLetters -Default $Global:Default
+ UserShellFolder -UserFolder Music -FolderPath "${SelectedDrive}:\Music" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Pictures
+ # Изображения
+ Write-Verbose -Message $Localization.PicturesDriveSelect -Verbose
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.PicturesRequest
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ $SelectedDrive = ShowMenu -Title $Localization.PicturesDriveSelect -Menu $DriveLetters -Default $Global:Default
+ UserShellFolder -UserFolder Pictures -FolderPath "${SelectedDrive}:\Pictures" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Videos
+ # Видео
+ Write-Verbose -Message $Localization.VideosDriveSelect -Verbose
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.VideosRequest
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ $SelectedDrive = ShowMenu -Title $Localization.VideosDriveSelect -Menu $DriveLetters -Default $Global:Default
+ UserShellFolder -UserFolder Videos -FolderPath "${SelectedDrive}:\Videos" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+ }
+ "Custom"
+ {
+ # Desktop
+ # Рабочий стол
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.DesktopFolderSelect
+ $Select = $Localization.Select
+ $Skip = $Localization.Skip
+ $Options = "&$Select", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $FolderBrowserDialog = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog
+ $FolderBrowserDialog.Description = $Localization.FolderSelect
+ $FolderBrowserDialog.RootFolder = "MyComputer"
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $FolderBrowserDialog.ShowDialog($Focus)
+
+ if ($FolderBrowserDialog.SelectedPath)
+ {
+ UserShellFolder -UserFolder Desktop -FolderPath $FolderBrowserDialog.SelectedPath -RemoveDesktopINI
+ Write-Verbose -Message ($Localization.NewUserFolderLocation -f $FolderBrowserDialog.SelectedPath) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Documents
+ # Документы
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.DocumentsFolderSelect
+ $Select = $Localization.Select
+ $Skip = $Localization.Skip
+ $Options = "&$Select", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $FolderBrowserDialog = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog
+ $FolderBrowserDialog.Description = $Localization.FolderSelect
+ $FolderBrowserDialog.RootFolder = "MyComputer"
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $FolderBrowserDialog.ShowDialog($Focus)
+
+ if ($FolderBrowserDialog.SelectedPath)
+ {
+ UserShellFolder -UserFolder Documents -FolderPath $FolderBrowserDialog.SelectedPath -RemoveDesktopINI
+ Write-Verbose -Message ($Localization.NewUserFolderLocation -f $FolderBrowserDialog.SelectedPath) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Downloads
+ # Загрузки
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.DownloadsFolderSelect
+ $Select = $Localization.Select
+ $Skip = $Localization.Skip
+ $Options = "&$Select", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $FolderBrowserDialog = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog
+ $FolderBrowserDialog.Description = $Localization.FolderSelect
+ $FolderBrowserDialog.RootFolder = "MyComputer"
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $FolderBrowserDialog.ShowDialog($Focus)
+
+ if ($FolderBrowserDialog.SelectedPath)
+ {
+ UserShellFolder -UserFolder Downloads -FolderPath $FolderBrowserDialog.SelectedPath -RemoveDesktopINI
+ Write-Verbose -Message ($Localization.NewUserFolderLocation -f $FolderBrowserDialog.SelectedPath) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Music
+ # Музыка
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.MusicFolderSelect
+ $Select = $Localization.Select
+ $Skip = $Localization.Skip
+ $Options = "&$Select", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $FolderBrowserDialog = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog
+ $FolderBrowserDialog.Description = $Localization.FolderSelect
+ $FolderBrowserDialog.RootFolder = "MyComputer"
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $FolderBrowserDialog.ShowDialog($Focus)
+
+ if ($FolderBrowserDialog.SelectedPath)
+ {
+ UserShellFolder -UserFolder Music -FolderPath $FolderBrowserDialog.SelectedPath -RemoveDesktopINI
+ Write-Verbose -Message ($Localization.NewUserFolderLocation -f $FolderBrowserDialog.SelectedPath) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Pictures
+ # Изображения
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.PicturesFolderSelect
+ $Select = $Localization.Select
+ $Skip = $Localization.Skip
+ $Options = "&$Select", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $FolderBrowserDialog = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog
+ $FolderBrowserDialog.Description = $Localization.FolderSelect
+ $FolderBrowserDialog.RootFolder = "MyComputer"
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $FolderBrowserDialog.ShowDialog($Focus)
+
+ if ($FolderBrowserDialog.SelectedPath)
+ {
+ UserShellFolder -UserFolder Pictures -FolderPath $FolderBrowserDialog.SelectedPath -RemoveDesktopINI
+ Write-Verbose -Message ($Localization.NewUserFolderLocation -f $FolderBrowserDialog.SelectedPath) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Videos
+ # Видео
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.VideosFolderSelect
+ $Select = $Localization.Select
+ $Skip = $Localization.Skip
+ $Options = "&$Select", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $FolderBrowserDialog = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog
+ $FolderBrowserDialog.Description = $Localization.FolderSelect
+ $FolderBrowserDialog.RootFolder = "MyComputer"
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $FolderBrowserDialog.ShowDialog($Focus)
+
+ if ($FolderBrowserDialog.SelectedPath)
+ {
+ UserShellFolder -UserFolder Videos -FolderPath $FolderBrowserDialog.SelectedPath -RemoveDesktopINI
+ Write-Verbose -Message ($Localization.NewUserFolderLocation -f $FolderBrowserDialog.SelectedPath) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+ }
+ "Default"
+ {
+ # Desktop
+ # Рабочий стол
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.DesktopDefaultFolder
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ UserShellFolder -UserFolder Desktop -FolderPath "$env:USERPROFILE\Desktop" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Documents
+ # Документы
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.DocumentsDefaultFolder
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ UserShellFolder -UserFolder Documents -FolderPath "$env:USERPROFILE\Documents" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Downloads
+ # Загрузки
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.DownloadsDefaultFolder
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ UserShellFolder -UserFolder Downloads -FolderPath "$env:USERPROFILE\Downloads" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Music
+ # Музыка
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.MusicDefaultFolder
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ UserShellFolder -UserFolder Music -FolderPath "$env:USERPROFILE\Music" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Pictures
+ # Изображения
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.PicturesDefaultFolder
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ UserShellFolder -UserFolder Pictures -FolderPath "$env:USERPROFILE\Pictures" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+
+ # Videos
+ # Видео
+ Write-Warning -Message $Localization.FilesWontBeMoved
+
+ $Title = ""
+ $Message = $Localization.VideosDefaultFolder
+ $Change = $Localization.Change
+ $Skip = $Localization.Skip
+ $Options = "&$Change", "&$Skip"
+ $DefaultChoice = 1
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+
+ switch ($Result)
+ {
+ "0"
+ {
+ UserShellFolder -UserFolder Videos -FolderPath "$env:USERPROFILE\Videos" -RemoveDesktopINI
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Save screenshots by pressing Win+PrtScr to the Desktop/Pictures folder
+ Сохранять скриншоты по нажатию Win+PrtScr в папку "Рабочий стол"/"Изображения"
+
+ .PARAMETER Desktop
+ Save screenshots by pressing Win+PrtScr to the Desktop folder
+ Сохранять скриншоты по нажатию Win+PrtScr в папку "Рабочий стол"
+
+ .PARAMETER Default
+ Save screenshots by pressing Win+PrtScr to the Pictures folder
+ Сохранять скриншоты по нажатию Win+PrtScr в папку "Изображения"
+
+ .EXAMPLE
+ WinPrtScrFolder -Desktop
+
+ .EXAMPLE
+ WinPrtScrFolder -Default
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function WinPrtScrFolder
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Desktop"
+ )]
+ [switch]
+ $Desktop,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Default"
+ )]
+ [switch]
+ $Default
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Desktop"
+ {
+ $DesktopFolder = Get-ItemPropertyValue -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name Desktop
+ Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name "{B7BEDE81-DF94-4682-A7D8-57A52620B86F}" -Type ExpandString -Value $DesktopFolder -Force
+ }
+ "Default"
+ {
+ Remove-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name "{B7BEDE81-DF94-4682-A7D8-57A52620B86F}" -Force -ErrorAction SilentlyContinue
+ }
+ }
+
+ # Save all opened folders in order to restore them after File Explorer restart
+ # Сохранить все открытые папки, чтобы восстановить их после перезапуска проводника
+ Clear-Variable -Name OpenedFolders -Force -ErrorAction Ignore
+ $OpenedFolders = {(New-Object -ComObject Shell.Application).Windows() | ForEach-Object -Process {$_.Document.Folder.Self.Path}}.Invoke()
+
+ # In order for the changes to take effect the File Explorer process has to be restarted
+ # Чтобы изменения вступили в силу, необходимо перезапустить процесс проводника
+ Stop-Process -Name explorer -Force
+
+ # Restoring closed folders
+ # Восстановить закрытые папки
+ foreach ($OpenedFolder in $OpenedFolders)
+ {
+ if (Test-Path -Path $OpenedFolder)
+ {
+ Invoke-Item -Path $OpenedFolder
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Launch/do not launch folder windows in a separate process
+ Запускать/не запускать окна с папками в отдельном процессе
+
+ .PARAMETER Enable
+ Launch launch folder windows in a separate process
+ Запускать окна с папками в отдельном процессе
+
+ .PARAMETER Disable
+ Do not launch folder windows in a separate process
+ Не запускать окна с папками в отдельном процессе
+
+ .EXAMPLE
+ FoldersLaunchSeparateProcess -Enable
+
+ .EXAMPLE
+ FoldersLaunchSeparateProcess -Disable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function FoldersLaunchSeparateProcess
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SeparateProcess -PropertyType DWord -Value 1 -Force
+ }
+ "Disable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SeparateProcess -PropertyType DWord -Value 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable help lookup via F1
+ Отключить/включить открытие справки по нажатию F1
+
+ .PARAMETER Enable
+ Enable help lookup via F1
+ Включить открытие справки по нажатию F1
+
+ .PARAMETER Disable
+ Disable help lookup via F1
+ Отключить открытие справки по нажатию F1
+
+ .EXAMPLE
+ F1HelpPage -Enable
+
+ .EXAMPLE
+ F1HelpPage -Disable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function F1HelpPage
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ Remove-Item -Path "HKCU:\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}" -Recurse -Force -ErrorAction SilentlyContinue
+ }
+ "Disable"
+ {
+ if (-not (Test-Path -Path "HKCU:\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win64"))
+ {
+ New-Item -Path "HKCU:\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win64" -Force
+ }
+ New-ItemProperty -Path "HKCU:\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win64" -Name "(Default)" -PropertyType String -Value "" -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Enable/disable Num Lock at startup
+ Включить/выключить Num Lock при загрузке
+
+ .PARAMETER Enable
+ Enable Num Lock at startup
+ Включить Num Lock при загрузке
+
+ .PARAMETER Disable
+ Disable Num Lock at startup
+ Выключить Num Lock при загрузке
+
+ .EXAMPLE
+ NumLock -Enable
+
+ .EXAMPLE
+ NumLock -Disable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function NumLock
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ New-ItemProperty -Path "Registry::HKEY_USERS\.DEFAULT\Control Panel\Keyboard" -Name InitialKeyboardIndicators -PropertyType String -Value 2147483650 -Force
+ }
+ "Disable"
+ {
+ New-ItemProperty -Path "Registry::HKEY_USERS\.DEFAULT\Control Panel\Keyboard" -Name InitialKeyboardIndicators -PropertyType String -Value 2147483648 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable StickyKey after tapping the Shift key 5 times
+ Выключить/включить залипание клавиши Shift после 5 нажатий
+
+ .PARAMETER Enable
+ Enable StickyKey after tapping the Shift key 5 times
+ Включить залипание клавиши Shift после 5 нажатий
+
+ .PARAMETER Disable
+ Disable StickyKey after tapping the Shift key 5 times
+ Выключить залипание клавиши Shift после 5 нажатий
+
+ .EXAMPLE
+ StickyShift -Enable
+
+ .EXAMPLE
+ StickyShift -Disable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function StickyShift
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ New-ItemProperty -Path "HKCU:\Control Panel\Accessibility\StickyKeys" -Name Flags -PropertyType String -Value 510 -Force
+ }
+ "Disable"
+ {
+ New-ItemProperty -Path "HKCU:\Control Panel\Accessibility\StickyKeys" -Name Flags -PropertyType String -Value 506 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable AutoPlay for all media and devices
+ Выключить/включить автозапуск для всех носителей и устройств
+
+ .PARAMETER Enable
+ Disable/enable AutoPlay for all media and devices
+ Выключить/включить автозапуск для всех носителей и устройств
+
+ .PARAMETER Disable
+ Disable/enable AutoPlay for all media and devices
+ Выключить/включить автозапуск для всех носителей и устройств
+
+ .EXAMPLE
+ Autoplay -Enable
+
+ .EXAMPLE
+ Autoplay -Disable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function Autoplay
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -PropertyType DWord -Value 0 -Force
+ }
+ "Disable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable thumbnail cache removal
+ Выключить/включить удаление кэша миниатюр
+
+ .PARAMETER Enable
+ Enable thumbnail cache removal
+ Включить удаление кэша миниатюр
+
+ .PARAMETER Disable
+ Disable thumbnail cache removal
+ Выключить удаление кэша миниатюр
+
+ .EXAMPLE
+ ThumbnailCacheRemoval -Enable
+
+ .EXAMPLE
+ ThumbnailCacheRemoval -Disable
+#>
+function ThumbnailCacheRemoval
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ New-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Thumbnail Cache" -Name Autorun -PropertyType DWord -Value 3 -Force
+ }
+ "Disable"
+ {
+ New-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Thumbnail Cache" -Name Autorun -PropertyType DWord -Value 0 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Enable/disable "Network Discovery" and "File and Printers Sharing" for workgroup networks
+ Включить/выключить сетевое обнаружение и общий доступ к файлам и принтерам для рабочих групп
+
+ .PARAMETER Enable
+ Enable "Network Discovery" and "File and Printers Sharing" for workgroup networks
+ Включить сетевое обнаружение и общий доступ к файлам и принтерам для рабочих групп
+
+ .PARAMETER Disable
+ Disable "Network Discovery" and "File and Printers Sharing" for workgroup networks
+ Выключить сетевое обнаружение и общий доступ к файлам и принтерам для рабочих групп
+
+ .EXAMPLE
+ NetworkDiscovery -Enable
+
+ .EXAMPLE
+ NetworkDiscovery -Disable
+#>
+function NetworkDiscovery
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ $FirewallRules = @(
+ # File and printer sharing
+ # Общий доступ к файлам и принтерам
+ "@FirewallAPI.dll,-32752",
+
+ # Network discovery
+ # Сетевое обнаружение
+ "@FirewallAPI.dll,-28502"
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ if ((Get-CimInstance -ClassName CIM_ComputerSystem).PartOfDomain -eq $false)
+ {
+ Set-NetFirewallRule -Group $FirewallRules -Profile Private -Enabled True
+
+ Set-NetFirewallRule -Profile Public, Private -Name FPS-SMB-In-TCP -Enabled True
+ Set-NetConnectionProfile -NetworkCategory Private
+ }
+ }
+ "Disable"
+ {
+ if ((Get-CimInstance -ClassName CIM_ComputerSystem).PartOfDomain -eq $false)
+ {
+ Set-NetFirewallRule -Group $FirewallRules -Profile Private -Enabled False
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Enable/disable automatically adjusting active hours for me based on daily usage
+ Включить/выключить автоматическое изменение периода активности для этого устройства на основе действий
+
+ .PARAMETER Enable
+ Enable automatically adjusting active hours for me based on daily usage
+ Включить автоматическое изменение периода активности для этого устройства на основе действий
+
+ .PARAMETER Disable
+ Disable automatically adjusting active hours for me based on daily usage
+ Выключить автоматическое изменение периода активности для этого устройства на основе действий
+
+ .EXAMPLE
+ SmartActiveHours -Enable
+
+ .EXAMPLE
+ SmartActiveHours -Disable
+#>
+function SmartActiveHours
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name SmartActiveHoursState -PropertyType DWord -Value 1 -Force
+ }
+ "Disable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name SmartActiveHoursState -PropertyType DWord -Value 2 -Force
+ }
+ }
+}
+#endregion System
+
+#region Start menu
+<#
+ .SYNOPSIS
+ Hide/show recently added apps in the Start menu
+ Скрывать/показывать недавно добавленные приложения в меню "Пуск"
+
+ .PARAMETER Hide
+ Hide recently added apps in the Start menu
+ Скрывать недавно добавленные приложения в меню "Пуск"
+
+ .PARAMETER Show
+ Show recently added apps in the Start menu
+ Показывать недавно добавленные приложения в меню "Пуск"
+
+ .EXAMPLE
+ RecentlyAddedApps -Hide
+
+ .EXAMPLE
+ RecentlyAddedApps -Show
+#>
+function RecentlyAddedApps
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ 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 HideRecentlyAddedApps -PropertyType DWord -Value 1 -Force
+ }
+ "Show"
+ {
+ Remove-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name HideRecentlyAddedApps -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show app suggestions in the Start menu
+ Скрывать/показывать рекомендации в меню "Пуск"
+
+ .PARAMETER Hide
+ Hide app suggestions in the Start menu
+ Скрывать рекомендации в меню "Пуск"
+
+ .PARAMETER Show
+ Show app suggestions in the Start menu
+ Показывать рекомендации в меню "Пуск"
+
+ .EXAMPLE
+ AppSuggestions -Hide
+
+ .EXAMPLE
+ AppSuggestions -Show
+#>
+function AppSuggestions
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338388Enabled -PropertyType DWord -Value 0 -Force
+ }
+ "Show"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338388Enabled -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Run the Command Prompt shortcut from the Start menu as Administrator/user
+ Запускать ярлык командной строки в меню "Пуск" от имени Администратора/пользователя
+
+ .PARAMETER Elevated
+ Run the Command Prompt shortcut from the Start menu as Administrator
+ Запускать ярлык командной строки в меню "Пуск" от имени Администратора
+
+ .PARAMETER NonElevated
+ Run the Command Prompt shortcut from the Start menu as user
+ Запускать ярлык командной строки в меню "Пуск" от имени пользователя
+
+ .EXAMPLE
+ RunCMDShortcut -Elevated
+
+ .EXAMPLE
+ RunCMDShortcut -NonElevated
+#>
+function RunCMDShortcut
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Elevated"
+ )]
+ [switch]
+ $Elevated,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "NonElevated"
+ )]
+ [switch]
+ $NonElevated
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Elevated"
+ {
+ [byte[]]$bytes = Get-Content -Path "$env:APPDATA\Microsoft\Windows\Start menu\Programs\System Tools\Command Prompt.lnk" -Encoding Byte -Raw
+ $bytes[0x15] = $bytes[0x15] -bor 0x20
+ Set-Content -Path "$env:APPDATA\Microsoft\Windows\Start menu\Programs\System Tools\Command Prompt.lnk" -Value $bytes -Encoding Byte -Force
+ }
+ "NonElevated"
+ {
+ [byte[]]$bytes = Get-Content -Path "$env:APPDATA\Microsoft\Windows\Start menu\Programs\System Tools\Command Prompt.lnk" -Encoding Byte -Raw
+ $bytes[0x15] = $bytes[0x15] -bxor 0x20
+ Set-Content -Path "$env:APPDATA\Microsoft\Windows\Start menu\Programs\System Tools\Command Prompt.lnk" -Value $bytes -Encoding Byte -Force
+ }
+ }
+}
+#endregion Start menu
+
+#region Gaming
+<#
+ .SYNOPSIS
+ Disable/enable Xbox Game Bar
+ Выключить/включить Xbox Game Bar
+
+ .PARAMETER Disable
+ Disable Xbox Game Bar
+ Выключить Xbox Game Bar
+
+ .PARAMETER Enable
+ Enable Xbox Game Bar
+ Включить Xbox Game Bar
+
+ .EXAMPLE
+ XboxGameBar -Disable
+
+ .EXAMPLE
+ XboxGameBar -Enable
+#>
+function XboxGameBar
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ if ((Get-AppxPackage -Name Microsoft.XboxGamingOverlay) -or (Get-AppxPackage -Name Microsoft.GamingApp))
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\GameDVR -Name AppCaptureEnabled -PropertyType DWord -Value 0 -Force
+ New-ItemProperty -Path HKCU:\System\GameConfigStore -Name GameDVR_Enabled -PropertyType DWord -Value 0 -Force
+ }
+ }
+ "Enable"
+ {
+ if ((Get-AppxPackage -Name Microsoft.XboxGamingOverlay) -or (Get-AppxPackage -Name Microsoft.GamingApp))
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\GameDVR -Name AppCaptureEnabled -PropertyType DWord -Value 1 -Force
+ New-ItemProperty -Path HKCU:\System\GameConfigStore -Name GameDVR_Enabled -PropertyType DWord -Value 1 -Force
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable Xbox Game Bar tips
+ Выключить/включить советы Xbox Game Bar
+
+ .PARAMETER Disable
+ Disable Xbox Game Bar tips
+ Выключить советы Xbox Game Bar
+
+ .PARAMETER Enable
+ Enable Xbox Game Bar tips
+ Включить советы Xbox Game Bar
+
+ .EXAMPLE
+ XboxGameTips -Disable
+
+ .EXAMPLE
+ XboxGameTips -Enable
+#>
+function XboxGameTips
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ if ((Get-AppxPackage -Name Microsoft.XboxGamingOverlay) -or (Get-AppxPackage -Name Microsoft.GamingApp))
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\GameBar -Name ShowStartupPanel -PropertyType DWord -Value 0 -Force
+ }
+ }
+ "Enable"
+ {
+ if ((Get-AppxPackage -Name Microsoft.XboxGamingOverlay) -or (Get-AppxPackage -Name Microsoft.GamingApp))
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\GameBar -Name ShowStartupPanel -PropertyType DWord -Value 1 -Force
+ }
+ }
+ }
+}
+
+<#
+ Set "High performance" in graphics performance preference for an app
+ Only with a dedicated GPU
+
+ Установить параметры производительности графики для отдельных приложений на "Высокая производительность"
+ Только при наличии внешней видеокарты
+#>
+function SetAppGraphicsPerformance
+{
+ if (Get-CimInstance -ClassName Win32_VideoController | Where-Object -FilterScript {$_.AdapterDACType -ne "Internal" -and $null -ne $_.AdapterDACType})
+ {
+ $Title = $Localization.GraphicsPerformanceTitle
+ $Message = $Localization.GraphicsPerformanceRequest
+ $Add = $Localization.Add
+ $Skip = $Localization.Skip
+ $Options = "&$Add", "&$Skip"
+ $DefaultChoice = 1
+
+ do
+ {
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $OpenFileDialog = New-Object -TypeName System.Windows.Forms.OpenFileDialog
+ $OpenFileDialog.Filter = $Localization.EXEFilesFilter
+ $OpenFileDialog.InitialDirectory = "${env:ProgramFiles(x86)}"
+ $OpenFileDialog.Multiselect = $false
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $OpenFileDialog.ShowDialog($Focus)
+
+ if ($OpenFileDialog.FileName)
+ {
+ if (-not (Test-Path -Path HKCU:\SOFTWARE\Microsoft\DirectX\UserGpuPreferences))
+ {
+ New-Item -Path HKCU:\SOFTWARE\Microsoft\DirectX\UserGpuPreferences -Force
+ }
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\DirectX\UserGpuPreferences -Name $OpenFileDialog.FileName -PropertyType String -Value "GpuPreference=2;" -Force
+ Write-Verbose -Message ("{0}" -f $OpenFileDialog.FileName) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+ }
+ until ($Result -eq 1)
+ }
+}
+#endregion Gaming
+
+#region Scheduled tasks
+<#
+ .SYNOPSIS
+ Create/delete the "Windows Cleanup" task to clean up unused files and Windows updates in the Task Scheduler
+ Создать/удалить задачу "Windows Cleanup" в Планировщике задач по очистке неиспользуемых файлов и обновлений Windows
+
+ .PARAMETER Register
+ Create the "Windows Cleanup" task to clean up unused files and Windows updates in the Task Scheduler
+ Создать задачу "Windows Cleanup" в Планировщике задач по очистке неиспользуемых файлов и обновлений Windows
+
+ .PARAMETER Delete
+ Delete the "Windows Cleanup" task to clean up unused files and Windows updates from the Task Scheduler
+ Удалить задачу "Windows Cleanup" из Планировщика задач по очистке неиспользуемых файлов и обновлений Windows
+
+ .EXAMPLE
+ CleanUpTask -Register
+
+ .EXAMPLE
+ CleanUpTask -Delete
+
+ .NOTES
+ A minute before the task starts, a warning in the Windows action center will appear
+ The task runs every 90 days
+
+ За минуту до выполнения задачи в Центре уведомлений Windows появится предупреждение
+ Задача выполняется каждые 90 дней
+#>
+function CleanUpTask
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Register"
+ )]
+ [switch]
+ $Register,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Delete"
+ )]
+ [switch]
+ $Delete
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Register"
+ {
+ Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches | ForEach-Object -Process {
+ Remove-ItemProperty -Path $_.PsPath -Name StateFlags1337 -Force -ErrorAction Ignore
+ }
+
+ $VolumeCaches = @(
+ # Delivery Optimization Files
+ # Файлы оптимизации доставки
+ "Delivery Optimization Files",
+
+ # Device driver packages
+ # Пакеты драйверов устройств
+ "Device Driver Packages",
+
+ # Previous Windows Installation(s)
+ # Предыдущие установки Windows
+ "Previous Installations",
+
+ # Setup log files
+ # Файлы журнала установки
+ "Setup Log Files",
+
+ # Temporary Setup Files
+ # Временные файлы установки
+ "Temporary Setup Files",
+
+ # Microsoft Defender
+ "Windows Defender",
+
+ # Windows upgrade log files
+ # Файлы журнала обновления Windows
+ "Windows Upgrade Log Files"
+ )
+ foreach ($VolumeCache in $VolumeCaches)
+ {
+ New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\$VolumeCache" -Name StateFlags1337 -PropertyType DWord -Value 2 -Force
+ }
+
+ $TaskScript = @"
+`$cleanmgr = """{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\cleanmgr.exe"""
+
+[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
+`$Template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText01)
+
+`$ToastXML = [xml]`$Template.GetXml()
+`$ToastXML.GetElementsByTagName("""text""").AppendChild(`$ToastXML.CreateTextNode("""$($Localization.CleanUpTaskToast)"""))
+
+`$XML = New-Object -TypeName Windows.Data.Xml.Dom.XmlDocument
+`$XML.LoadXml(`$ToastXML.OuterXml)
+[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(`$cleanmgr).Show(`$XML)
+
+Get-Process -Name cleanmgr | Stop-Process -Force
+
+Start-Sleep -Seconds 60
+
+`$ProcessInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo
+`$ProcessInfo.FileName = """$env:SystemRoot\system32\cleanmgr.exe"""
+`$ProcessInfo.Arguments = """/sagerun:1337"""
+`$ProcessInfo.UseShellExecute = `$true
+`$ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Minimized
+
+`$Process = New-Object -TypeName System.Diagnostics.Process
+`$Process.StartInfo = `$ProcessInfo
+`$Process.Start() | Out-Null
+
+Start-Sleep -Seconds 3
+
+[int]`$SourceMainWindowHandle = (Get-Process -Name cleanmgr | Where-Object -FilterScript {`$_.PriorityClass -eq """BelowNormal"""}).MainWindowHandle
+
+function MinimizeWindow
+{
+ [CmdletBinding()]
+ param
+ (
+ [Parameter(Mandatory = `$true)]
+ `$Process
+ )
+
+ `$ShowWindowAsync = @{
+ Namespace = """WinAPI"""
+ Name = """Win32ShowWindowAsync"""
+ Language = """CSharp"""
+ MemberDefinition = @'
+[DllImport("""user32.dll""")]
+public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
+'@
+ }
+ if (-not ("""WinAPI.Win32ShowWindowAsync""" -as [type]))
+ {
+ Add-Type @ShowWindowAsync
+ }
+ `$MainWindowHandle = (Get-Process -Name `$Process | Where-Object -FilterScript {`$_.PriorityClass -eq """BelowNormal"""}).MainWindowHandle
+ [WinAPI.Win32ShowWindowAsync]::ShowWindowAsync(`$MainWindowHandle, 2)
+}
+
+while (`$true)
+{
+ [int]`$CurrentMainWindowHandle = (Get-Process -Name cleanmgr | Where-Object -FilterScript {`$_.PriorityClass -eq """BelowNormal"""}).MainWindowHandle
+ if (`$SourceMainWindowHandle -ne `$CurrentMainWindowHandle)
+ {
+ MinimizeWindow -Process cleanmgr
+ break
+ }
+ Start-Sleep -Milliseconds 5
+}
+
+`$ProcessInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo
+`$ProcessInfo.FileName = """`$env:SystemRoot\system32\dism.exe"""
+`$ProcessInfo.Arguments = """/Online /English /Cleanup-Image /StartComponentCleanup /NoRestart"""
+`$ProcessInfo.UseShellExecute = `$true
+`$ProcessInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Minimized
+
+`$Process = New-Object -TypeName System.Diagnostics.Process
+`$Process.StartInfo = `$ProcessInfo
+`$Process.Start() | Out-Null
+"@
+
+ $Action = New-ScheduledTaskAction -Execute powershell.exe -Argument "-WindowStyle Hidden -Command $TaskScript"
+ $Trigger = New-ScheduledTaskTrigger -Daily -DaysInterval 90 -At 9am
+ $Settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -StartWhenAvailable
+ $Principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -RunLevel Highest
+ $Description = $Localization.CleanUpTaskDescription
+ $Parameters = @{
+ "TaskName" = "Windows Cleanup"
+ "TaskPath" = "Sophia Script"
+ "Principal" = $Principal
+ "Action" = $Action
+ "Description" = $Description
+ "Settings" = $Settings
+ "Trigger" = $Trigger
+ }
+ Register-ScheduledTask @Parameters -Force
+ }
+ "Delete"
+ {
+ Unregister-ScheduledTask -TaskName "Windows Cleanup" -Confirm:$false
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Create/delete the "SoftwareDistribution" task to clear the %SystemRoot%\SoftwareDistribution\Download folder in the Task Scheduler
+ Создать/удалить задачу "SoftwareDistribution" в Планировщике задач по очистке папки %SystemRoot%\SoftwareDistribution\Download
+
+ .PARAMETER Register
+ Create the "SoftwareDistribution" task to clear the %SystemRoot%\SoftwareDistribution\Download folder in the Task Scheduler
+ Создать задачу "SoftwareDistribution" в Планировщике задач по очистке папки %SystemRoot%\SoftwareDistribution\Download
+
+ .PARAMETER Delete
+ Delete the "SoftwareDistribution" task to clear the %SystemRoot%\SoftwareDistribution\Download folder from the Task Scheduler
+ Удалить задачу "SoftwareDistribution" из Планировщика задач по очистке папки %SystemRoot%\SoftwareDistribution\Download
+
+ .EXAMPLE
+ SoftwareDistributionTask -Register
+
+ .EXAMPLE
+ SoftwareDistributionTask -Delete
+
+ .NOTES
+ The task runs on Thursdays every 4 weeks
+ Задача выполняется по четвергам каждую 4 неделю
+#>
+function SoftwareDistributionTask
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Register"
+ )]
+ [switch]
+ $Register,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Delete"
+ )]
+ [switch]
+ $Delete
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Register"
+ {
+ $Argument = @"
+(Get-Service -Name wuauserv).WaitForStatus('Stopped', '01:00:00')
+Get-ChildItem -Path $env:SystemRoot\SoftwareDistribution\Download -Recurse -Force | Remove-Item -Recurse -Force
+"@
+ $Action = New-ScheduledTaskAction -Execute powershell.exe -Argument $Argument
+ $Trigger = New-JobTrigger -Weekly -WeeksInterval 4 -DaysOfWeek Thursday -At 9am
+ $Settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -StartWhenAvailable
+ $Principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -RunLevel Highest
+ $Description = $Localization.FolderTaskDescription -f "$env:SystemRoot\SoftwareDistribution\Download"
+ $Parameters = @{
+ "TaskName" = "SoftwareDistribution"
+ "TaskPath" = "Sophia Script"
+ "Principal" = $Principal
+ "Action" = $Action
+ "Description" = $Description
+ "Settings" = $Settings
+ "Trigger" = $Trigger
+ }
+ Register-ScheduledTask @Parameters -Force
+ }
+ "Delete"
+ {
+ Unregister-ScheduledTask -TaskName SoftwareDistribution -Confirm:$false
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Create the "Temp" task to clear the %TEMP% folder in the Task Scheduler
+ Создать задачу "Temp" в Планировщике задач по очистке папки %TEMP%
+
+ .PARAMETER Register
+ Create the "Temp" to clear the %TEMP% folder in the Task Scheduler
+ Создать задачу "Temp" в Планировщике задач по очистке папки %TEMP%
+
+ .PARAMETER Delete
+ Delete the "Temp" task to clear the %TEMP% folder from the Task Scheduler
+ Удалить задачу "Temp" из Планировщика задач по очистке папки %TEMP%
+
+ .EXAMPLE
+ TempTask -Register
+
+ .EXAMPLE
+ TempTask -Delete
+
+ .NOTES
+ The task runs every 62 days
+ Задача выполняется каждые 62 дня
+#>
+function TempTask
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Register"
+ )]
+ [switch]
+ $Register,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Delete"
+ )]
+ [switch]
+ $Delete
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Register"
+ {
+ $Argument = "Get-ChildItem -Path $env:TEMP -Force -Recurse | Remove-Item -Recurse -Force"
+ $Action = New-ScheduledTaskAction -Execute powershell.exe -Argument $Argument
+ $Trigger = New-ScheduledTaskTrigger -Daily -DaysInterval 62 -At 9am
+ $Settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -StartWhenAvailable
+ $Principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -RunLevel Highest
+ $Description = $Localization.FolderTaskDescription
+ $Parameters = @{
+ "TaskName" = "Temp"
+ "TaskPath" = "Sophia Script"
+ "Principal" = $Principal
+ "Action" = $Action
+ "Description" = $Description
+ "Settings" = $Settings
+ "Trigger" = $Trigger
+ }
+ Register-ScheduledTask @Parameters -Force
+ }
+ "Delete"
+ {
+ Unregister-ScheduledTask -TaskName Temp -Confirm:$false
+ }
+ }
+}
+#endregion Scheduled tasks
+
+#region Windows Defender & Security
+# Enable Controlled folder access and add protected folders
+# Включить контролируемый доступ к папкам и добавить защищенные папки
+function AddProtectedFolders
+{
+ $Title = $Localization.ControlledFolderAccess
+ $Message = $Localization.ProtectedFoldersRequest
+ $Add = $Localization.Add
+ $Skip = $Localization.Skip
+ $Options = "&$Add", "&$Skip"
+ $DefaultChoice = 1
+
+ do
+ {
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $FolderBrowserDialog = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog
+ $FolderBrowserDialog.Description = $Localization.FolderSelect
+ $FolderBrowserDialog.RootFolder = "MyComputer"
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $FolderBrowserDialog.ShowDialog($Focus)
+
+ if ($FolderBrowserDialog.SelectedPath)
+ {
+ Set-MpPreference -EnableControlledFolderAccess Enabled
+ Add-MpPreference -ControlledFolderAccessProtectedFolders $FolderBrowserDialog.SelectedPath -Force
+ Write-Verbose -Message ("{0}" -f $FolderBrowserDialog.SelectedPath) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+ }
+ until ($Result -eq 1)
+}
+
+# Remove all added protected folders
+# Удалить все добавленные защищенные папки
+function RemoveProtectedFolders
+{
+ if ($null -ne (Get-MpPreference).ControlledFolderAccessProtectedFolders)
+ {
+ (Get-MpPreference).ControlledFolderAccessProtectedFolders | Format-Table -AutoSize -Wrap
+ Remove-MpPreference -ControlledFolderAccessProtectedFolders (Get-MpPreference).ControlledFolderAccessProtectedFolders -Force
+ Write-Verbose -Message $Localization.ProtectedFoldersListRemoved -Verbose
+ }
+}
+
+# Allow an app through Controlled folder access
+# Разрешить работу приложения через контролируемый доступ к папкам
+function AddAppControlledFolder
+{
+ $Title = $Localization.ControlledFolderAccess
+ $Message = $Localization.AppControlledFolderRequest
+ $Add = $Localization.Add
+ $Skip = $Localization.Skip
+ $Options = "&$Add", "&$Skip"
+ $DefaultChoice = 1
+
+ do
+ {
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $OpenFileDialog = New-Object -TypeName System.Windows.Forms.OpenFileDialog
+ $OpenFileDialog.Filter = $Localization.EXEFilesFilter
+ $OpenFileDialog.InitialDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
+ $OpenFileDialog.Multiselect = $false
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $OpenFileDialog.ShowDialog($Focus)
+
+ if ($OpenFileDialog.FileName)
+ {
+ Add-MpPreference -ControlledFolderAccessAllowedApplications $OpenFileDialog.FileName -Force
+ Write-Verbose -Message ("{0}" -f $OpenFileDialog.FileName) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+ }
+ until ($Result -eq 1)
+}
+
+# Remove all allowed apps through Controlled folder access
+# Удалить все добавленные разрешенные приложение через контролируемый доступ к папкам
+function RemoveAllowedAppsControlledFolder
+{
+ if ($null -ne (Get-MpPreference).ControlledFolderAccessAllowedApplications)
+ {
+ (Get-MpPreference).ControlledFolderAccessAllowedApplications | Format-Table -AutoSize -Wrap
+ Remove-MpPreference -ControlledFolderAccessAllowedApplications (Get-MpPreference).ControlledFolderAccessAllowedApplications -Force
+ Write-Verbose -Message $Localization.AllowedControlledFolderAppsRemoved -Verbose
+ }
+}
+
+# Add a folder to the exclusion from Microsoft Defender scanning
+# Добавить папку в список исключений сканирования Microsoft Defender
+function AddDefenderExclusionFolder
+{
+ $Title = $Localization.DefenderTitle
+ $Message = $Localization.DefenderExclusionFolderRequest
+ $Add = $Localization.Add
+ $Skip = $Localization.Skip
+ $Options = "&$Add", "&$Skip"
+ $DefaultChoice = 1
+
+ do
+ {
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $FolderBrowserDialog = New-Object -TypeName System.Windows.Forms.FolderBrowserDialog
+ $FolderBrowserDialog.Description = $Localization.FolderSelect
+ $FolderBrowserDialog.RootFolder = "MyComputer"
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $FolderBrowserDialog.ShowDialog($Focus)
+
+ if ($FolderBrowserDialog.SelectedPath)
+ {
+ Add-MpPreference -ExclusionPath $FolderBrowserDialog.SelectedPath -Force
+ Write-Verbose -Message ("{0}" -f $FolderBrowserDialog.SelectedPath) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+ }
+ until ($Result -eq 1)
+}
+
+# Remove all excluded folders from Microsoft Defender scanning
+# Удалить все папки из списка исключений сканирования Microsoft Defender
+function RemoveDefenderExclusionFolders
+{
+ if ($null -ne (Get-MpPreference).ExclusionPath)
+ {
+ $ExcludedFolders = (Get-Item -Path (Get-MpPreference).ExclusionPath -Force -ErrorAction Ignore | Where-Object -FilterScript {$_.Attributes -match "Directory"}).FullName
+ $ExcludedFolders | Format-Table -AutoSize -Wrap
+ Remove-MpPreference -ExclusionPath $ExcludedFolders -Force
+ Write-Verbose -Message $Localization.DefenderExclusionFoldersListRemoved -Verbose
+ }
+}
+
+# Add a file to the exclusion from Microsoft Defender scanning
+# Добавить файл в список исключений сканирования Microsoft Defender
+function AddDefenderExclusionFile
+{
+ $Title = "Microsoft Defender"
+ $Message = $Localization.AddDefenderExclusionFileRequest
+ $Add = $Localization.Add
+ $Skip = $Localization.Skip
+ $Options = "&$Add", "&$Skip"
+ $DefaultChoice = 1
+
+ do
+ {
+ $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
+ switch ($Result)
+ {
+ "0"
+ {
+ Add-Type -AssemblyName System.Windows.Forms
+ $OpenFileDialog = New-Object -TypeName System.Windows.Forms.OpenFileDialog
+ $OpenFileDialog.Filter = $Localization.AllFilesFilter
+ $OpenFileDialog.InitialDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
+ $OpenFileDialog.Multiselect = $false
+
+ # Focus on open file dialog
+ # Перевести фокус на диалог открытия файла
+ $Focus = New-Object -TypeName System.Windows.Forms.Form -Property @{TopMost = $true}
+ $OpenFileDialog.ShowDialog($Focus)
+
+ if ($OpenFileDialog.FileName)
+ {
+ Add-MpPreference -ExclusionPath $OpenFileDialog.FileName -Force
+ Write-Verbose -Message ("{0}" -f $OpenFileDialog.FileName) -Verbose
+ }
+ }
+ "1"
+ {
+ Write-Verbose -Message $Localization.Skipped -Verbose
+ }
+ }
+ }
+ until ($Result -eq 1)
+}
+
+# Remove all excluded files from Microsoft Defender scanning
+# Удалить все файлы из списка исключений сканирования Microsoft Defender
+function RemoveDefenderExclusionFiles
+{
+ if ($null -ne (Get-MpPreference).ExclusionPath)
+ {
+ $ExcludedFiles = (Get-Item -Path (Get-MpPreference).ExclusionPath -Force -ErrorAction Ignore | Where-Object -FilterScript {$_.Attributes -notmatch "Directory"}).FullName
+ $ExcludedFiles | Format-Table -AutoSize -Wrap
+ Remove-MpPreference -ExclusionPath $ExcludedFiles -Force
+ Write-Verbose -Message $Localization.DefenderExclusionFilesRemoved -Verbose
+ }
+}
+
+<#
+ .SYNOPSIS
+ Enable/disable Microsoft Defender Exploit Guard network protection
+ Включить/выключить защиту сети в Microsoft Defender Exploit Guard
+
+ .PARAMETER Disable
+ Disable Microsoft Defender Exploit Guard network protection
+ Выключить защиту сети в Microsoft Defender Exploit Guard
+
+ .PARAMETER Enable
+ Enable Microsoft Defender Exploit Guard network protection
+ Включить защиту сети в Microsoft Defender Exploit Guard
+
+ .EXAMPLE
+ NetworkProtection -Disable
+
+ .EXAMPLE
+ NetworkProtection -Enable
+#>
+function NetworkProtection
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ Set-MpPreference -EnableNetworkProtection Disabled
+ }
+ "Enable"
+ {
+ Set-MpPreference -EnableNetworkProtection Enabled
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Enable/disable detection for potentially unwanted applications and block them
+ Включить/выключить обнаружение потенциально нежелательных приложений и блокировать их
+
+ .PARAMETER Disable
+ Enable/disable detection for potentially unwanted applications and block them
+ Включить/выключить обнаружение потенциально нежелательных приложений и блокировать их
+
+ .PARAMETER Enable
+ Enable/disable detection for potentially unwanted applications and block them
+ Включить/выключить обнаружение потенциально нежелательных приложений и блокировать их
+
+ .EXAMPLE
+ PUAppsDetection -Disable
+
+ .EXAMPLE
+ PUAppsDetection -Enable
+#>
+function PUAppsDetection
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ Set-MpPreference -PUAProtection Disabled
+ }
+ "Enable"
+ {
+ Set-MpPreference -PUAProtection Enabled
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Enable/disable sandboxing for Microsoft Defender
+ Включить/выключить песочницу для Microsoft Defender
+
+ .PARAMETER Disable
+ Disable sandboxing for Microsoft Defender
+ Выключить песочницу для Microsoft Defender
+
+ .PARAMETER Enable
+ Enable sandboxing for Microsoft Defender
+ Включить песочницу для Microsoft Defender
+
+ .EXAMPLE
+ DefenderSandbox -Disable
+
+ .EXAMPLE
+ DefenderSandbox -Enable
+#>
+function DefenderSandbox
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ setx /M MP_FORCE_USE_SANDBOX 0
+ }
+ "Enable"
+ {
+ setx /M MP_FORCE_USE_SANDBOX 1
+ }
+ }
+}
+
+# Dismiss Microsoft Defender offer in the Windows Security about signing in Microsoft account
+# Отклонить предложение Microsoft Defender в "Безопасность Windows" о входе в аккаунт Microsoft
+function DismissMSAccount
+{
+ New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows Security Health\State" -Name AccountProtection_MicrosoftAccount_Disconnected -PropertyType DWord -Value 1 -Force
+}
+
+# Dismiss Microsoft Defender offer in the Windows Security about turning on the SmartScreen filter for Microsoft Edge
+# Отклонить предложение Microsoft Defender в "Безопасность Windows" включить фильтр SmartScreen для Microsoft Edge
+function DismissSmartScreenFilter
+{
+ New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows Security Health\State" -Name AppAndBrowser_EdgeSmartScreenOff -PropertyType DWord -Value 0 -Force
+}
+
+<#
+ .SYNOPSIS
+ Enable/disable events auditing generated when a process is created or starts
+ Включить/выключить аудит событий, возникающих при создании или запуске процесса
+
+ .PARAMETER Disable
+ Disable events auditing generated when a process is created or starts
+ Выключить аудит событий, возникающих при создании или запуске процесса
+
+ .PARAMETER Enable
+ Enable events auditing generated when a process is created or starts
+ Включить аудит событий, возникающих при создании или запуске процесса
+
+ .EXAMPLE
+ AuditProcess -Disable
+
+ .EXAMPLE
+ AuditProcess -Enable
+#>
+function AuditProcess
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ auditpol /set /subcategory:"{0CCE922B-69AE-11D9-BED3-505054503030}" /success:disable /failure:disable
+ }
+ "Enable"
+ {
+ auditpol /set /subcategory:"{0CCE922B-69AE-11D9-BED3-505054503030}" /success:enable /failure:enable
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Include/do not include command line in process creation events
+ Включать/не включать командную строку в событиях создания процесса
+
+ .PARAMETER Disable
+ Do not include command line in process creation events
+ Не включать командную строку в событиях создания процесса
+
+ .PARAMETER Enable
+ Include command line in process creation events
+ Включать командную строку в событиях создания процесса
+
+ .EXAMPLE
+ AuditCommandLineProcess -Disable
+
+ .EXAMPLE
+ AuditCommandLineProcess -Enable
+
+ .NOTES
+ In order this feature to work events auditing ("AuditProcess -Enable" function) will be enabled
+ Для того, чтобы работал данный функционал, будет включен аудит событий (функция "AuditProcess -Enable")
+#>
+function AuditCommandLineProcess
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit -Name ProcessCreationIncludeCmdLine_Enabled -Force -ErrorAction SilentlyContinue
+ }
+ "Enable"
+ {
+ # Enable events auditing generated when a process is created or starts
+ # Включить аудит событий, возникающих при создании или запуске процесса
+ auditpol /set /subcategory:"{0CCE922B-69AE-11D9-BED3-505054503030}" /success:enable /failure:enable
+
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit -Name ProcessCreationIncludeCmdLine_Enabled -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Create/remove "Process Creation" Event Viewer Custom View
+ Создать/удалить настаиваемое представление "Создание процесса" в Просмотре событий
+
+ .PARAMETER Disable
+ Remove "Process Creation" Event Viewer Custom View
+ Удалить настаиваемое представление "Создание процесса" в Просмотре событий
+
+ .PARAMETER Enable
+ Create "Process Creation" Event Viewer Custom View
+ Создать настаиваемое представление "Создание процесса" в Просмотре событий
+
+ .EXAMPLE
+ EventViewerCustomView -Disable
+
+ .EXAMPLE
+ EventViewerCustomView -Enable
+
+ .NOTES
+ In order this feature to work events auditing ("AuditProcess -Enable" function) and command line in process creation events will be enabled
+ Для того, чтобы работал данный функционал, буден включен аудит событий (функция "AuditProcess -Enable") и командной строки в событиях создания процесса
+#>
+function EventViewerCustomView
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ Remove-Item -Path "$env:ProgramData\Microsoft\Event Viewer\Views\ProcessCreation.xml" -Force -ErrorAction SilentlyContinue
+ }
+ "Enable"
+ {
+ # Enable events auditing generated when a process is created or starts
+ # Включить аудит событий, возникающих при создании или запуске процесса
+ auditpol /set /subcategory:"{0CCE922B-69AE-11D9-BED3-505054503030}" /success:enable /failure:enable
+
+ # Include command line in process creation events
+ # Включать командную строку в событиях создания процесса
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit -Name ProcessCreationIncludeCmdLine_Enabled -PropertyType DWord -Value 1 -Force
+
+ $XML = @"
+
+
+
+
+
+
+ $($Localization.EventViewerCustomViewName)
+ $($Localization.EventViewerCustomViewDescription)
+
+
+
+
+
+
+
+
+"@
+ if (-not (Test-Path -Path "$env:ProgramData\Microsoft\Event Viewer\Views"))
+ {
+ New-Item -Path "$env:ProgramData\Microsoft\Event Viewer\Views" -ItemType Directory -Force
+ }
+
+ # Saving ProcessCreation.xml in UTF-8 encoding
+ # Сохраняем ProcessCreation.xml в кодировке UTF-8
+ Set-Content -Path "$env:ProgramData\Microsoft\Event Viewer\Views\ProcessCreation.xml" -Value $XML -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Enable/disable logging for all Windows PowerShell modules
+ Включить/выключить ведение журнала для всех модулей Windows PowerShell
+
+ .PARAMETER Disable
+ Disable logging for all Windows PowerShell modules
+ Выключить ведение журнала для всех модулей Windows PowerShell
+
+ .PARAMETER Enable
+ Enable logging for all Windows PowerShell modules
+ Включить ведение журнала для всех модулей Windows PowerShell
+
+ .EXAMPLE
+ PowerShellModulesLogging -Disable
+
+ .EXAMPLE
+ PowerShellModulesLogging -Enable
+#>
+function PowerShellModulesLogging
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ Remove-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging -Name EnableModuleLogging -Force -ErrorAction SilentlyContinue
+ Remove-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames -Name * -Force -ErrorAction SilentlyContinue
+ }
+ "Enable"
+ {
+ if (-not (Test-Path -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames))
+ {
+ New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames -Force
+ }
+ New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging -Name EnableModuleLogging -PropertyType DWord -Value 1 -Force
+ New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames -Name * -PropertyType String -Value * -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Enable/disable logging for all PowerShell scripts input to the Windows PowerShell event log
+ Включить/выключить ведение журнала для всех вводимых сценариев PowerShell в журнале событий Windows PowerShell
+
+ .PARAMETER Disable
+ Disable logging for all PowerShell scripts input to the Windows PowerShell event log
+ Выключить ведение журнала для всех вводимых сценариев PowerShell в журнале событий Windows PowerShell
+
+ .PARAMETER Enable
+ Enable logging for all PowerShell scripts input to the Windows PowerShell event log
+ Включить ведение журнала для всех вводимых сценариев PowerShell в журнале событий Windows PowerShell
+
+ .EXAMPLE
+ PowerShellScriptsLogging -Disable
+
+ .EXAMPLE
+ PowerShellScriptsLogging -Enable
+#>
+function PowerShellScriptsLogging
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ Remove-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging -Name EnableScriptBlockLogging -Force -ErrorAction SilentlyContinue
+ }
+ "Enable"
+ {
+ if (-not (Test-Path -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging))
+ {
+ New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging -Force
+ }
+ New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging -Name EnableScriptBlockLogging -PropertyType DWord -Value 1 -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable apps and files checking within Microsofot Defender SmartScreen
+ Выключить/включить проверку приложений и файлов фильтром SmartScreen в Microsoft Defender
+
+ .PARAMETER Disable
+ Disable apps and files checking within Microsofot Defender SmartScreen
+ Выключить проверку приложений и файлов фильтром SmartScreen в Microsoft Defender
+
+ .PARAMETER Enable
+ Enable apps and files checking within Microsofot Defender SmartScreen
+ Включить проверку приложений и файлов фильтром SmartScreen в Microsoft Defender
+
+ .EXAMPLE
+ AppsSmartScreen -Disable
+
+ .EXAMPLE
+ AppsSmartScreen -Enable
+#>
+function AppsSmartScreen
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name SmartScreenEnabled -PropertyType String -Value Off -Force
+ }
+ "Enable"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name SmartScreenEnabled -PropertyType String -Value Warn -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable the Attachment Manager marking files that have been downloaded from the Internet as unsafe
+ Выключить/включить проверку Диспетчером вложений файлов, скачанных из интернета как небезопасные
+
+ .PARAMETER Disable
+ Disable the Attachment Manager marking files that have been downloaded from the Internet as unsafe
+ Выключить проверку Диспетчером вложений файлов, скачанных из интернета как небезопасные
+
+ .PARAMETER Enable
+ Enable the Attachment Manager marking files that have been downloaded from the Internet as unsafe
+ Включить проверку Диспетчером вложений файлов, скачанных из интернета как небезопасные
+
+ .EXAMPLE
+ SaveZoneInformation -Disable
+
+ .EXAMPLE
+ SaveZoneInformation -Enable
+
+ .NOTES
+ Current user only
+ Только для текущего пользователя
+#>
+function SaveZoneInformation
+{
+ 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\Windows\CurrentVersion\Policies\Attachments))
+ {
+ New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Attachments -Force
+ }
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Attachments -Name SaveZoneInformation -PropertyType DWord -Value 1 -Force
+ }
+ "Enable"
+ {
+ Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Attachments -Name SaveZoneInformation -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable Windows Script Host
+ Выключить/включить Windows Script Host
+
+ .PARAMETER Disable
+ Disable Windows Script Host
+ Выключить Windows Script Host
+
+ .PARAMETER Enable
+ Enable Windows Script Host
+ Включить Windows Script Host
+
+ .EXAMPLE
+ WindowsScriptHost -Disable
+
+ .EXAMPLE
+ WindowsScriptHost -Enable
+
+ .NOTES
+ Current user only
+ It becomes impossible to run .js and .vbs files
+
+ Только для текущего пользователя
+ Становится невозможным запустить файлы .js и .vbs
+#>
+function WindowsScriptHost
+{
+ 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\Windows Script Host\Settings"))
+ {
+ New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows Script Host\Settings" -Force
+ }
+ New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows Script Host\Settings" -Name Enabled -PropertyType DWord -Value 0 -Force
+ }
+ "Enable"
+ {
+ Remove-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows Script Host\Settings" -Name Enabled -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Disable/enable Windows Sandbox
+ Выключить/включить Windows Sandbox
+
+ .PARAMETER Disable
+ Disable Windows Sandbox
+ Выключить Windows Sandbox
+
+ .PARAMETER Enable
+ Enable Windows Sandbox
+ Включить Windows Sandbox
+
+ .EXAMPLE
+ WindowsSandbox -Disable
+
+ .EXAMPLE
+ WindowsSandbox -Enable
+#>
+function WindowsSandbox
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Disable"
+ {
+ if (Get-WindowsEdition -Online | Where-Object -FilterScript {$_.Edition -eq "Professional" -or $_.Edition -like "Enterprise*"})
+ {
+ # Checking whether x86 virtualization is enabled in the firmware
+ # Проверка: включена ли в настройках UEFI аппаратная виртуализация x86
+ if ((Get-CimInstance -ClassName CIM_Processor).VirtualizationFirmwareEnabled -eq $true)
+ {
+ Disable-WindowsOptionalFeature -FeatureName Containers-DisposableClientVM -Online -NoRestart
+ }
+ else
+ {
+ try
+ {
+ # Determining whether Hyper-V is enabled
+ # Проверка: включен ли Hyper-V
+ if ((Get-CimInstance -ClassName CIM_ComputerSystem).HypervisorPresent -eq $true)
+ {
+ Disable-WindowsOptionalFeature -FeatureName Containers-DisposableClientVM -Online -NoRestart
+ }
+ }
+ catch [System.Exception]
+ {
+ Write-Error -Message $Localization.EnableHardwareVT -ErrorAction SilentlyContinue
+ }
+ }
+ }
+ }
+ "Enable"
+ {
+ if (Get-WindowsEdition -Online | Where-Object -FilterScript {$_.Edition -eq "Professional" -or $_.Edition -like "Enterprise*"})
+ {
+ # Checking whether x86 virtualization is enabled in the firmware
+ # Проверка: включена ли в настройках UEFI аппаратная виртуализация x86
+ if ((Get-CimInstance -ClassName CIM_Processor).VirtualizationFirmwareEnabled -eq $true)
+ {
+ Enable-WindowsOptionalFeature -FeatureName Containers-DisposableClientVM -All -Online -NoRestart
+ }
+ else
+ {
+ try
+ {
+ # Determining whether Hyper-V is enabled
+ # Проверка: включен ли Hyper-V
+ if ((Get-CimInstance -ClassName CIM_ComputerSystem).HypervisorPresent -eq $true)
+ {
+ Enable-WindowsOptionalFeature -FeatureName Containers-DisposableClientVM -All -Online -NoRestart
+ }
+ }
+ catch [System.Exception]
+ {
+ Write-Error -Message $Localization.EnableHardwareVT -ErrorAction SilentlyContinue
+ }
+ }
+ }
+ }
+ }
+}
+#endregion Windows Defender & Security
+
+#region Context menu
+<#
+ .SYNOPSIS
+ Add/remove the "Extract all" item to Windows Installer (.msi) context menu
+ Добавить/удалить пункт "Извлечь все" в контекстное меню Windows Installer (.msi)
+
+ .PARAMETER Remove
+ Remove the "Extract all" item to Windows Installer (.msi) context menu
+ Удалить пункт "Извлечь все" в контекстное меню Windows Installer (.msi)
+
+ .PARAMETER Add
+ Add the "Extract all" item to Windows Installer (.msi) context menu
+ Добавить пункт "Извлечь все" в контекстное меню Windows Installer (.msi)
+
+ .EXAMPLE
+ MSIExtractContext -Remove
+
+ .EXAMPLE
+ MSIExtractContext -Add
+#>
+function MSIExtractContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Remove"
+ )]
+ [switch]
+ $Remove,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Add"
+ )]
+ [switch]
+ $Add
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Remove"
+ {
+ Remove-Item -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract -Recurse -Force -ErrorAction SilentlyContinue
+ }
+ "Add"
+ {
+ if (-not (Test-Path -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract\Command))
+ {
+ New-Item -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract\Command -Force
+ }
+ $Value = "{0}" -f 'msiexec.exe /a "%1" /qb TARGETDIR="%1 extracted"'
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract\Command -Name "(Default)" -PropertyType String -Value $Value -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract -Name MUIVerb -PropertyType String -Value "@shell32.dll,-37514" -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract -Name Icon -PropertyType String -Value "shell32.dll,-16817" -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Add/remove the "Install" item to the .cab archives context menu
+ Добавить/удалить пункт "Установить" в контекстное меню .cab архивов
+
+ .PARAMETER Remove
+ Remove the "Install" item to the .cab archives context menu
+ Удалить пункт "Установить" в контекстное меню .cab архивов
+
+ .PARAMETER Add
+ Add the "Install" item to the .cab archives context menu
+ Добавить пункт "Установить" в контекстное меню .cab архивов
+
+ .EXAMPLE
+ CABInstallContext -Remove
+
+ .EXAMPLE
+ CABInstallContext -Add
+#>
+function CABInstallContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Remove"
+ )]
+ [switch]
+ $Remove,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Add"
+ )]
+ [switch]
+ $Add
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Remove"
+ {
+ Remove-Item -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs\Command -Recurse -Force -ErrorAction SilentlyContinue
+ }
+ "Add"
+ {
+ if (-not (Test-Path -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs\Command))
+ {
+ New-Item -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs\Command -Force
+ }
+ $Value = "{0}" -f "cmd /c DISM.exe /Online /Add-Package /PackagePath:`"%1`" /NoRestart & pause"
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs\Command -Name "(Default)" -PropertyType String -Value $Value -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs -Name MUIVerb -PropertyType String -Value "@shell32.dll,-10210" -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs -Name HasLUAShield -PropertyType String -Value "" -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Add/remove the "Run as different user" item to the .exe files types context menu
+ Добавить/удалить пункт "Запуск от имени другого пользователя" в контекстное меню .exe файлов
+
+ .PARAMETER Remove
+ Remove the "Run as different user" item to the .exe files types context menu
+ Удалить пункт "Запуск от имени другого пользователя" в контекстное меню .exe файлов
+
+ .PARAMETER Add
+ Add the "Run as different user" item to the .exe files types context menu
+ Добавить пункт "Запуск от имени другого пользователя" в контекстное меню .exe файлов
+
+ .EXAMPLE
+ RunAsDifferentUserContext -Remove
+
+ .EXAMPLE
+ RunAsDifferentUserContext -Add
+#>
+function RunAsDifferentUserContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Remove"
+ )]
+ [switch]
+ $Remove,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Add"
+ )]
+ [switch]
+ $Add
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Remove"
+ {
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\exefile\shell\runasuser -Name Extended -PropertyType String -Value "" -Force
+ }
+ "Add"
+ {
+ Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\exefile\shell\runasuser -Name Extended -Force -ErrorAction Ignore
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "Cast to Device" item from the context menu
+ Отобразить/скрыть пункт "Передать на устройство" из контекстного меню
+
+ .PARAMETER Hide
+ Hide the "Cast to Device" item from the context menu
+ Скрыть пункт "Передать на устройство" из контекстного меню
+
+ .PARAMETER Show
+ Show the "Cast to Device" item from the context menu
+ Отобразить пункт "Передать на устройство" из контекстного меню
+
+ .EXAMPLE
+ CastToDeviceContext -Hide
+
+ .EXAMPLE
+ CastToDeviceContext -Show
+#>
+function CastToDeviceContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ if (-not (Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked"))
+ {
+ New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Force
+ }
+ New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Name "{7AD84985-87B4-4a16-BE58-8B72A5B390F7}" -PropertyType String -Value "Play to menu" -Force
+ }
+ "Show"
+ {
+ Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Name "{7AD84985-87B4-4a16-BE58-8B72A5B390F7}" -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "Share" item from the context menu
+ Отобразить/скрыть пункт "Отправить" (поделиться) из контекстного меню
+
+ .PARAMETER Hide
+ Hide the "Share" item from the context menu
+ Скрыть пункт "Отправить" (поделиться) из контекстного меню
+
+ .PARAMETER Show
+ Show the "Share" item from the context menu
+ Отобразить пункт "Отправить" (поделиться) из контекстного меню
+
+ .EXAMPLE
+ ShareContext -Hide
+
+ .EXAMPLE
+ ShareContext -Show
+#>
+function ShareContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ if (-not (Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked"))
+ {
+ New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Force
+ }
+ New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Name "{E2BF9676-5F8F-435C-97EB-11607A5BEDF7}" -PropertyType String -Value "" -Force
+ }
+ "Show"
+ {
+ Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Name "{E2BF9676-5F8F-435C-97EB-11607A5BEDF7}" -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "Edit with Paint 3D" item from the context menu
+ Отобразить/скрыть пункт "Изменить с помощью Paint 3D" из контекстного меню
+
+ .PARAMETER Hide
+ Hide the "Edit with Paint 3D" item from the context menu
+ Скрыть пункт "Изменить с помощью Paint 3D" из контекстного меню
+
+ .PARAMETER Show
+ Show the "Edit with Paint 3D" item from the context menu
+ Отобразить пункт "Изменить с помощью Paint 3D" из контекстного меню
+
+ .EXAMPLE
+ EditWithPaint3DContext -Hide
+
+ .EXAMPLE
+ EditWithPaint3DContext -Show
+#>
+function EditWithPaint3DContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ $Extensions = @(".bmp", ".gif", ".jpe", ".jpeg", ".jpg", ".png", ".tif", ".tiff")
+ foreach ($extension in $extensions)
+ {
+ New-ItemProperty -Path "Registry::HKEY_CLASSES_ROOT\SystemFileAssociations\$Extension\Shell\3D Edit" -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+ }
+ }
+ "Show"
+ {
+ $Extensions = @(".bmp", ".gif", ".jpe", ".jpeg", ".jpg", ".png", ".tif", ".tiff")
+ foreach ($Extension in $Extensions)
+ {
+ Remove-ItemProperty -Path "Registry::HKEY_CLASSES_ROOT\SystemFileAssociations\$Extension\Shell\3D Edit" -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "Print" item from the .bat and .cmd context menu
+ Отобразить/скрыть пункт "Печать" из контекстного меню .bat и .cmd файлов
+
+ .PARAMETER Hide
+ Hide the "Print" item from the .bat and .cmd context menu
+ Скрыть пункт "Печать" из контекстного меню .bat и .cmd файлов
+
+ .PARAMETER Show
+ Show the "Print" item from the .bat and .cmd context menu
+ Отобразить пункт "Печать" из контекстного меню .bat и .cmd файлов
+
+ .EXAMPLE
+ PrintCMDContext -Hide
+
+ .EXAMPLE
+ PrintCMDContext -Show
+#>
+function PrintCMDContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\batfile\shell\print -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\cmdfile\shell\print -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+ }
+ "Show"
+ {
+ Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\batfile\shell\print -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue
+ Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\cmdfile\shell\print -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "Include in Library" item from the context menu
+ Отобразить/скрыть пункт "Добавить в библиотеку" из контекстного меню
+
+ .PARAMETER Hide
+ Hide the "Include in Library" item from the context menu
+ Скрыть пункт "Добавить в библиотеку" из контекстного меню
+
+ .PARAMETER Show
+ Show the "Include in Library" item from the context menu
+ Отобразить пункт "Добавить в библиотеку" из контекстного меню
+
+ .EXAMPLE
+ IncludeInLibraryContext -Hide
+
+ .EXAMPLE
+ IncludeInLibraryContext -Show
+#>
+function IncludeInLibraryContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path "Registry::HKEY_CLASSES_ROOT\Folder\shellex\ContextMenuHandlers\Library Location" -Name "(Default)" -PropertyType String -Value "-{3dad6c5d-2167-4cae-9914-f99e41c12cfa}" -Force
+ }
+ "Show"
+ {
+ New-ItemProperty -Path "Registry::HKEY_CLASSES_ROOT\Folder\shellex\ContextMenuHandlers\Library Location" -Name "(Default)" -PropertyType String -Value "{3dad6c5d-2167-4cae-9914-f99e41c12cfa}" -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "Send to" item from the folders context menu
+ Отобразить/скрыть пункт "Отправить" из контекстного меню папок
+
+ .PARAMETER Hide
+ Hide the "Send to" item from the folders context menu
+ Скрыть пункт "Отправить" из контекстного меню папок
+
+ .PARAMETER Show
+ Show the "Send to" item from the folders context menu
+ Отобразить пункт "Отправить" из контекстного меню папок
+
+ .EXAMPLE
+ SendToContext -Hide
+
+ .EXAMPLE
+ SendToContext -Show
+#>
+function SendToContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\SendTo -Name "(Default)" -PropertyType String -Value "-{7BA4C740-9E81-11CF-99D3-00AA004AE837}" -Force
+ }
+ "Show"
+ {
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\SendTo -Name "(Default)" -PropertyType String -Value "{7BA4C740-9E81-11CF-99D3-00AA004AE837}" -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "Turn on BitLocker" item from the context menu
+ Отобразить/скрыть пункт "Включить BitLocker" из контекстного меню
+
+ .PARAMETER Hide
+ Hide the "Turn on BitLocker" item from the context menu
+ Скрыть пункт "Включить BitLocker" из контекстного меню
+
+ .PARAMETER Show
+ Show the "Turn on BitLocker" item from the context menu
+ Отобразить пункт "Включить BitLocker" из контекстного меню
+
+ .EXAMPLE
+ BitLockerContext -Hide
+
+ .EXAMPLE
+ BitLockerContext -Show
+#>
+function BitLockerContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ if (Get-WindowsEdition -Online | Where-Object -FilterScript {$_.Edition -eq "Professional" -or $_.Edition -like "Enterprise*"})
+ {
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\encrypt-bde -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\encrypt-bde-elev -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\manage-bde -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\resume-bde -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\resume-bde-elev -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\unlock-bde -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force
+ }
+ }
+ "Show"
+ {
+ if (Get-WindowsEdition -Online | Where-Object -FilterScript {$_.Edition -eq "Professional" -or $_.Edition -like "Enterprise*"})
+ {
+ Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\encrypt-bde -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue
+ Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\encrypt-bde-elev -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue
+ Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\manage-bde -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue
+ Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\resume-bde -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue
+ Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\resume-bde-elev -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue
+ Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Drive\shell\unlock-bde -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Add/remove the "Bitmap image" item from the "New" context menu
+ Добавить/удалить пункт "Точечный рисунок" из контекстного меню "Создать"
+
+ .PARAMETER Remove
+ Remove the "Bitmap image" item from the "New" context menu
+ Удалить пункт "Точечный рисунок" из контекстного меню "Создать"
+
+ .PARAMETER Add
+ Add the "Bitmap image" item from the "New" context menu
+ Добавить пункт "Точечный рисунок" из контекстного меню "Создать"
+
+ .EXAMPLE
+ BitmapImageNewContext -Remove
+
+ .EXAMPLE
+ BitmapImageNewContext -Add
+#>
+function BitmapImageNewContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Remove"
+ )]
+ [switch]
+ $Remove,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Add"
+ )]
+ [switch]
+ $Add
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Remove"
+ {
+ if ((Get-WindowsCapability -Online -Name "Microsoft.Windows.MSPaint*").State -eq "Installed")
+ {
+ Remove-Item -Path Registry::HKEY_CLASSES_ROOT\.bmp\ShellNew -Force -ErrorAction SilentlyContinue
+ }
+ }
+ "Add"
+ {
+ if ((Get-WindowsCapability -Online -Name "Microsoft.Windows.MSPaint*").State -eq "Installed")
+ {
+ if (-not (Test-Path -Path Registry::HKEY_CLASSES_ROOT\.bmp\ShellNew))
+ {
+ New-Item -Path Registry::HKEY_CLASSES_ROOT\.bmp\ShellNew -Force
+ }
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\.bmp\ShellNew -Name ItemName -PropertyType ExpandString -Value "@%systemroot%\system32\mspaint.exe,-59414" -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\.bmp\ShellNew -Name NullFile -PropertyType String -Value "" -Force
+ }
+ else
+ {
+ Get-WindowsCapability -Online -Name "Microsoft.Windows.MSPaint*" | Add-WindowsCapability -Online
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Add/remove the "Rich Text Document" item from the "New" context menu
+ Добавить/удалить пункт "Документ в формате RTF" из контекстного меню "Создать"
+
+ .PARAMETER Remove
+ Remove the "Rich Text Document" item from the "New" context menu
+ Удалить пункт "Документ в формате RTF" из контекстного меню "Создать"
+
+ .PARAMETER Add
+ Add the "Rich Text Document" item from the "New" context menu
+ Добавить пункт "Документ в формате RTF" из контекстного меню "Создать"
+
+ .EXAMPLE
+ RichTextDocumentNewContext -Remove
+
+ .EXAMPLE
+ RichTextDocumentNewContext -Add
+#>
+function RichTextDocumentNewContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Remove"
+ )]
+ [switch]
+ $Remove,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Add"
+ )]
+ [switch]
+ $Add
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Remove"
+ {
+ if ((Get-WindowsCapability -Online -Name "Microsoft.Windows.WordPad*").State -eq "Installed")
+ {
+ Remove-Item -Path Registry::HKEY_CLASSES_ROOT\.rtf\ShellNew -Force -ErrorAction Ignore
+ }
+ }
+ "Add"
+ {
+ if ((Get-WindowsCapability -Online -Name "Microsoft.Windows.WordPad*").State -eq "Installed")
+ {
+ if (-not (Test-Path -Path Registry::HKEY_CLASSES_ROOT\.rtf\ShellNew))
+ {
+ New-Item -Path Registry::HKEY_CLASSES_ROOT\.rtf\ShellNew -Force
+ }
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\.rtf\ShellNew -Name Data -PropertyType String -Value "{\rtf1}" -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\.rtf\ShellNew -Name ItemName -PropertyType ExpandString -Value "@%ProgramFiles%\Windows NT\Accessories\WORDPAD.EXE,-213" -Force
+ }
+ else
+ {
+ Get-WindowsCapability -Online -Name "Microsoft.Windows.WordPad*" | Add-WindowsCapability -Online
+ }
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Add/remove the "Compressed (zipped) Folder" item from the "New" context menu
+ Добавить/удалить пункт "Сжатая ZIP-папка" из контекстного меню "Создать"
+
+ .PARAMETER Remove
+ Remove the "Compressed (zipped) Folder" item from the "New" context menu
+ Удалить пункт "Сжатая ZIP-папка" из контекстного меню "Создать"
+
+ .PARAMETER Add
+ Add the "Compressed (zipped) Folder" item from the "New" context menu
+ Добавить пункт "Сжатая ZIP-папка" из контекстного меню "Создать"
+
+ .EXAMPLE
+ CompressedFolderNewContext -Remove
+
+ .EXAMPLE
+ CompressedFolderNewContext -Add
+#>
+function CompressedFolderNewContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Remove"
+ )]
+ [switch]
+ $Remove,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Add"
+ )]
+ [switch]
+ $Add
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Remove"
+ {
+ Remove-Item -Path Registry::HKEY_CLASSES_ROOT\.zip\CompressedFolder\ShellNew -Force -ErrorAction Ignore
+ }
+ "Add"
+ {
+ if (-not (Test-Path -Path Registry::HKEY_CLASSES_ROOT\.zip\CompressedFolder\ShellNew))
+ {
+ New-Item -Path Registry::HKEY_CLASSES_ROOT\.zip\CompressedFolder\ShellNew -Force
+ }
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\.zip\CompressedFolder\ShellNew -Name Data -PropertyType Binary -Value ([byte[]](80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)) -Force
+ New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\.zip\CompressedFolder\ShellNew -Name ItemName -PropertyType ExpandString -Value "@%SystemRoot%\system32\zipfldr.dll,-10194" -Force
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Enable/disable the "Open", "Print", and "Edit" context menu items for more than 15 items selected
+ Включить/отключить элементы контекстного меню "Открыть", "Изменить" и "Печать" при выделении более 15 элементов
+
+ .PARAMETER Enable
+ Enable the "Open", "Print", and "Edit" context menu items for more than 15 items selected
+ Включить элементы контекстного меню "Открыть", "Изменить" и "Печать" при выделении более 15 элементов
+
+ .PARAMETER Disable
+ Disable the "Open", "Print", and "Edit" context menu items for more than 15 items selected
+ Отключить элементы контекстного меню "Открыть", "Изменить" и "Печать" при выделении более 15 элементов
+
+ .EXAMPLE
+ MultipleInvokeContext -Enable
+
+ .EXAMPLE
+ MultipleInvokeContext -Disable
+#>
+function MultipleInvokeContext
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Enable"
+ )]
+ [switch]
+ $Enable,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Disable"
+ )]
+ [switch]
+ $Disable
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Enable"
+ {
+ New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name MultipleInvokePromptMinimum -PropertyType DWord -Value 300 -Force
+ }
+ "Disable"
+ {
+ Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name MultipleInvokePromptMinimum -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "Look for an app in the Microsoft Store" item in the "Open with" dialog
+ Отобразить/скрыть пункт "Поиск приложения в Microsoft Store" в диалоге "Открыть с помощью"
+
+ .PARAMETER Hide
+ Hide the "Look for an app in the Microsoft Store" item in the "Open with" dialog
+ Скрыть пункт "Поиск приложения в Microsoft Store" в диалоге "Открыть с помощью"
+
+ .PARAMETER Show
+ Show the "Look for an app in the Microsoft Store" item in the "Open with" dialog
+ Отобразить пункт "Поиск приложения в Microsoft Store" в диалоге "Открыть с помощью"
+
+ .EXAMPLE
+ UseStoreOpenWith -Hide
+
+ .EXAMPLE
+ UseStoreOpenWith -Show
+#>
+function UseStoreOpenWith
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ 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 NoUseStoreOpenWith -PropertyType DWord -Value 1 -Force
+ }
+ "Show"
+ {
+ Remove-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name NoUseStoreOpenWith -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+
+<#
+ .SYNOPSIS
+ Hide/show the "Previous Versions" tab from files and folders context menu and also the "Restore previous versions" context menu item
+ Отобразить/скрыть вкладку "Предыдущие версии" в свойствах файлов и папок, а также пункт контекстного меню "Восстановить прежнюю версию"
+
+ .PARAMETER Hide
+ Hide the "Previous Versions" tab from files and folders context menu and also the "Restore previous versions" context menu item
+ Скрыть вкладку "Предыдущие версии" в свойствах файлов и папок, а также пункт контекстного меню "Восстановить прежнюю версию"
+
+ .PARAMETER Show
+ Show the "Previous Versions" tab from files and folders context menu and also the "Restore previous versions" context menu item
+ Отобразить вкладку "Предыдущие версии" в свойствах файлов и папок, а также пункт контекстного меню "Восстановить прежнюю версию"
+
+ .EXAMPLE
+ PreviousVersionsPage -Hide
+
+ .EXAMPLE
+ PreviousVersionsPage -Show
+#>
+function PreviousVersionsPage
+{
+ param
+ (
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Hide"
+ )]
+ [switch]
+ $Hide,
+
+ [Parameter(
+ Mandatory = $true,
+ ParameterSetName = "Show"
+ )]
+ [switch]
+ $Show
+ )
+
+ switch ($PSCmdlet.ParameterSetName)
+ {
+ "Hide"
+ {
+ New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name NoPreviousVersionsPage -PropertyType DWord -Value 1 -Force
+ }
+ "Show"
+ {
+ Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name NoPreviousVersionsPage -Force -ErrorAction SilentlyContinue
+ }
+ }
+}
+#endregion Context menu
+
+#region Refresh
+function Refresh
+{
+ $UpdateExplorer = @{
+ Namespace = "WinAPI"
+ Name = "UpdateExplorer"
+ Language = "CSharp"
+ MemberDefinition = @"
+private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
+private const int WM_SETTINGCHANGE = 0x1a;
+private const int SMTO_ABORTIFHUNG = 0x0002;
+
+[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
+static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);
+[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
+private static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, string lParam, int fuFlags, int uTimeout, IntPtr lpdwResult);
+[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = false)]
+private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
+public static void Refresh()
+{
+ // Update desktop icons
+ // Обновить иконки рабочего стола
+ SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
+
+ // Update environment variables
+ // Обновить переменные среды
+ SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, null, SMTO_ABORTIFHUNG, 100, IntPtr.Zero);
+
+ // Update taskbar
+ // Обновить панель задач
+ SendNotifyMessage(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, "TraySettings");
+}
+
+private static readonly IntPtr hWnd = new IntPtr(65535);
+private const int Msg = 273;
+// Virtual key ID of the F5 in File Explorer
+// Виртуальный код клавиши F5 в проводнике
+private static readonly UIntPtr UIntPtr = new UIntPtr(41504);
+
+[DllImport("user32.dll", SetLastError=true)]
+public static extern int PostMessageW(IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam);
+public static void PostMessage()
+{
+ // Simulate pressing F5 to refresh the desktop
+ // Симулировать нажатие F5 для обновления рабочего стола
+ PostMessageW(hWnd, Msg, UIntPtr, IntPtr.Zero);
+}
+"@
+ }
+ if (-not ("WinAPI.UpdateExplorer" -as [type]))
+ {
+ Add-Type @UpdateExplorer
+ }
+
+ # Simulate pressing F5 to refresh the desktop
+ # Симулировать нажатие F5 для обновления рабочего стола
+ [WinAPI.UpdateExplorer]::PostMessage()
+
+ # Refresh desktop icons, environment variables, taskbar
+ # Обновить иконки рабочего стола, переменные среды, панель задач
+ [WinAPI.UpdateExplorer]::Refresh()
+
+ # Restart the Start menu
+ # Перезапустить меню "Пуск"
+ Stop-Process -Name StartMenuExperienceHost -Force -ErrorAction Ignore
+
+ Write-Warning -Message $Localization.RestartWarning
+}
+#endregion Refresh
+
+# Errors output
+# Вывод ошибок
+function Errors
+{
+ if ($Global:Error)
+ {
+ ($Global:Error | ForEach-Object -Process {
+ [PSCustomObject] @{
+ $Localization.ErrorsLine = $_.InvocationInfo.ScriptLineNumber
+ $Localization.ErrorsFile = Split-Path -Path $PSCommandPath -Leaf
+ $Localization.ErrorsMessage = $_.Exception.Message
+ }
+ } | Sort-Object -Property Line | Format-Table -AutoSize -Wrap | Out-String).Trim()
+ }
+}
\ No newline at end of file
diff --git a/LTSC/cn-CN/Sophia.psd1 b/LTSC/cn-CN/Sophia.psd1
new file mode 100644
index 00000000..a7e3ea39
--- /dev/null
+++ b/LTSC/cn-CN/Sophia.psd1
@@ -0,0 +1,78 @@
+ConvertFrom-StringData -StringData @'
+UnsupportedOSBitness = 该脚本仅支持Windows 10 x64
+UnsupportedOSBuild = 该脚本支持Windows 10版本2004 / 20H1和更高版本
+ControlledFolderAccessDisabled = “受控文件夹访问”禁用
+ScheduledTasks = 计划任务
+ClearFolder = 删除"{0}"文件夹中的所有文件?
+FilesBlocked = 以下文件被第三方应用程序阻止。手动删除它们并继续
+TempNotEmpty = "{0}"文件夹不为空。 手动清除
+WindowsFeaturesWindowTitle = Windows功能
+FODWindowTitle = 移除可选功能 (FODv2)
+EnableHardwareVT = UEFI中开启虚拟化
+UserShellFolderNotEmpty = 一些文件留在了"{0}"文件夹.请手动将它们移到一个新位置
+RetrievingDrivesList = 取得驱动器列表...
+NewUserShellFolderLocation = 新位置:"{0}"
+DesktopDriveSelect = 请选择一个驱动器,桌面文件夹将创建在其根目录
+DocumentsDriveSelect = 请选择一个驱动器,文档文件夹将创建在其根目录
+DownloadsDriveSelect = 请选择一个驱动器,下载文件夹将创建在其根目录
+MusicDriveSelect = 请选择一个驱动器,音乐文件夹将创建在其根目录
+PicturesDriveSelect = 请选择一个驱动器,图片文件夹将创建在其根目录
+VideosDriveSelect = 请选择一个驱动器,视频文件夹将创建在其根目录
+DesktopRequest = 是否要更改桌面文件夹位置?
+DocumentsRequest = 是否要更改文档文件夹位置?
+DownloadsRequest = 是否要更改下载文件夹位置?
+MusicRequest = 是否要更改音乐文件夹位置?
+PicturesRequest = 是否要更改图片文件夹位置?
+VideosRequest = 是否要更改视频文件夹位置?
+DesktopFolderSelect = 为“桌面”文件夹选择一个文件夹
+DocumentsFolderSelect = 为“文档”文件夹选择一个文件夹
+DownloadsFolderSelect = 为“下载”文件夹选择一个文件夹
+MusicFolderSelect = 为“音乐”文件夹选择一个文件夹
+PicturesFolderSelect = 为“图片”文件夹选择一个文件夹
+VideosFolderSelect = 为“视频”文件夹选择一个文件夹
+DesktopDefaultFolder = 是否要将桌面文件夹位置改为默认值?
+DocumentsDefaultFolder = 是否要将文档文件夹位置改为默认值?
+DownloadsDefaultFolder = 是否要将下载文件夹位置改为默认值?
+MusicDefaultFolder = 是否要将音乐文件夹位置改为默认值?
+PicturesDefaultFolder = 是否要将图片文件夹位置改为默认值??
+VideosDefaultFolder = 是否要将视频文件夹位置改为默认值?
+GraphicsPerformanceTitle = 图形性能偏好
+GraphicsPerformanceRequest = 是否将所选应用程序的图形性能设置设为"高性能"?
+CleanUpTaskToast = 将在一分钟内清理未使用的Windows文件和更新
+CleanUpTaskDescription = 使用内置磁盘清理工具清理未使用的Windows文件和更新
+FolderTaskDescription = 定时清理"{0}"
+ControlledFolderAccess = 受控文件夹访问
+ProtectedFoldersRequest = 是否启用受控文件夹访问权限并指定文件夹,由微软Defender保护其免受恶意应用程序威胁?
+ProtectedFoldersListRemoved = 已被移除的文件夹
+AppControlledFolderRequest = 是否指定应用获取受控文件夹访问权限?
+AllowedControlledFolderAppsRemoved = 删除了允许的应用
+DefenderTitle = Microsoft Defender
+DefenderExclusionFolderRequest = 是否要添加指定文件夹到微软Defender的恶意软件扫描白名单?
+DefenderExclusionFoldersListRemoved = 排除的文件夹已删除
+AddDefenderExclusionFileRequest = 是否要添加指定文件到微软Defender的恶意软件扫描白名单?
+DefenderExclusionFilesRemoved = 排除文件已删除
+EventViewerCustomViewName = 进程创建
+EventViewerCustomViewDescription = 进程创建和命令行审核事件
+RestartWarning = 确保重启电脑
+ErrorsLine = 行
+ErrorsFile = 文件
+ErrorsMessage = 错误/警告
+Add = 添加
+AllFilesFilter = 所有文件 (*.*)|*.*
+Change = 更改
+Continue = 接续
+DialogBoxOpening = 显示对话窗口...
+Disable = 禁用
+Enable = 启用
+EXEFilesFilter = *.exe|*.exe|所有文件 (*.*)|*.*
+FolderSelect = 选择一个文件夹
+FilesWontBeMoved = 文件将不会被移动
+NoData = 无数据
+NoInternetConnection = 无网络连接
+Patient = 请等待...
+Select = 选择
+Skip = 跳过
+Skipped = 已跳过
+SymbolicSkipped = 跳过创建符号链接
+Uninstall = 卸载
+'@
diff --git a/LTSC/de-DE/Sophia.psd1 b/LTSC/de-DE/Sophia.psd1
new file mode 100644
index 00000000..7380d89e
--- /dev/null
+++ b/LTSC/de-DE/Sophia.psd1
@@ -0,0 +1,78 @@
+ConvertFrom-StringData -StringData @'
+UnsupportedOSBitness = Das Skript unterstützt nur Windows 10 x64
+UnsupportedOSBuild = Das Skript unterstützt Windows 10 2004 / 20H1-Versionen und höher
+ControlledFolderAccessDisabled = Kontrollierter Ordnerzugriff deaktiviert
+ScheduledTasks = Geplante Aufgaben
+ClearFolder = Löscht alle Dateien im Ordner "{0}"?
+FilesBlocked = Die folgenden Dateien werden von Apps von Drittanbietern blockiert. 'nEntfernen Sie sie manuell und fahren Sie fort
+TempNotEmpty = Der Ordner "{0}" ist nicht leer. Löschen Sie ihn manuell
+WindowsFeaturesWindowTitle = Windows Eigenschaften
+FODWindowTitle = Optionale eigenschaften (FODv2)
+EnableHardwareVT = Virtualisierung in UEFI aktivieren
+UserShellFolderNotEmpty = Einige im Ordner "{0}" verbliebene Dateien `nVerschieben Sie sie manuell an einen neuen Ort
+RetrievingDrivesList = Abrufen der Laufwerksliste...
+NewUserShellFolderLocation = Neuer Standort: "{0}"
+DesktopDriveSelect = Wählen Sie das Laufwerk, in dessen Stammverzeichnis der Desktop-Ordner erstellt werden soll
+DocumentsDriveSelect = Wählen Sie das Laufwerk, in dessen Stammverzeichnis der Ordner "Dokumente" erstellt werden soll
+DownloadsDriveSelect = Wählen Sie das Laufwerk, in dessen Stammverzeichnis der Ordner Downloads erstellt wird
+MusicDriveSelect = Wählen Sie das Laufwerk, in dessen Stammverzeichnis der Ordner "Musik" erstellt wird
+PicturesDriveSelect = Wählen Sie das Laufwerk, in dessen Stammverzeichnis der Ordner "Bilder" erstellt werden soll
+VideosDriveSelect = Wählen Sie das Laufwerk, in dessen Stammverzeichnis der Ordner Videos erstellt wird
+DesktopRequest = Möchten Sie den Speicherort des Desktop-Ordners ändern?
+DocumentsRequest = Möchten Sie den Speicherort des Ordners Dokumente ändern?
+DownloadsRequest = Möchten Sie den Speicherort des Ordners Downloads ändern?
+MusicRequest = Möchten Sie den Speicherort des Ordners Musik ändern?
+PicturesRequest = Möchten Sie den Speicherort des Ordners Bilder ändern?
+VideosRequest = Möchten Sie den Speicherort des Ordners Videos ändern?
+DesktopFolderSelect = Wählen Sie einen Ordner für den Ordner Desktop
+DocumentsFolderSelect = Wählen Sie einen Ordner für den Ordner Dokumente
+DownloadsFolderSelect = Wählen Sie einen Ordner für den Ordner Downloads
+MusicFolderSelect = Wählen Sie einen Ordner für den Ordner Musik
+PicturesFolderSelect = Wählen Sie einen Ordner für den Ordner Bilder aus
+VideosFolderSelect = Wählen Sie einen Ordner für den Ordner Videos
+DesktopDefaultFolder = Möchten Sie den Speicherort des Desktop-Ordners auf den Standardwert ändern?
+DocumentsDefaultFolder = Möchten Sie den Speicherort des Ordners Dokumente auf den Standardwert ändern?
+DownloadsDefaultFolder = Möchten Sie den Speicherort des Ordners Downloads auf den Standardwert ändern?
+MusicDefaultFolder = Möchten Sie den Speicherort des Ordners Musik auf den Standardwert ändern?
+PicturesDefaultFolder = Möchten Sie den Speicherort des Ordners "Bilder" auf den Standardwert ändern?
+VideosDefaultFolder = Möchten Sie den Speicherort des Ordners Videos auf den Standardwert ändern?
+GraphicsPerformanceTitle = Bevorzugte Grafikleistung
+GraphicsPerformanceRequest = Möchten Sie die Einstellung der Grafikleistung einer App Ihrer Wahl auf "Hohe Leistung" setzen?
+CleanUpTaskToast = Das Bereinigen ungenutzter Windows-Dateien und Updates beginnt in einer Minute
+CleanUpTaskDescription = Bereinigung ungenutzter Windows-Dateien und -Updates mit der integrierten Festplatten-Bereinigungsanwendung
+FolderTaskDescription = Die "{0}"-Ordnerbereinigung
+ControlledFolderAccess = Kontrollierter Ordner-Zugriff
+ProtectedFoldersRequest = Möchten Sie den kontrollierten Ordnerzugriff aktivieren und den Ordner angeben, den Microsoft Defender vor bösartigen Anwendungen und Bedrohungen schützen soll?
+ProtectedFoldersListRemoved = Gelöschte Ordner
+AppControlledFolderRequest = Möchten Sie eine Anwendung angeben, die über den Zugriff auf Kontrollierte Ordner erlaubt ist?
+AllowedControlledFolderAppsRemoved = Erlaubte Anwendungen entfernt
+DefenderTitle = Microsoft Defender
+DefenderExclusionFolderRequest = Möchten Sie einen Ordner angeben, der von den Malware-Scans von Microsoft Defender ausgeschlossen werden soll?
+DefenderExclusionFoldersListRemoved = Ausgeschlossene Ordner entfernt
+AddDefenderExclusionFileRequest = Möchten Sie eine Datei angeben, die von den Malware-Scans von Microsoft Defender ausgeschlossen werden soll?
+DefenderExclusionFilesRemoved = Ausgeschlossene Dateien entfernt
+EventViewerCustomViewName = Prozess-Erstellung
+EventViewerCustomViewDescription = Ereignisse zur Prozesserstellung und Befehlszeilen-Auditierung
+RestartWarning = Achten Sie darauf, Ihren PC neu zu starten
+ErrorsLine = Zeile
+ErrorsFile = Datei
+ErrorsMessage = Fehler/Warnungen
+Add = Hinzufügen
+AllFilesFilter = Alle Dateien (*.*)|*.*
+Change = Ändern
+Continue = Fortfahren
+DialogBoxOpening = Anzeigen des Dialogfensters...
+Disable = Deaktivieren
+Enable = Aktivieren
+EXEFilesFilter = *.exe|*.exe|Alle Dateien (*.*)|*.*
+FolderSelect = Wählen Sie einen Ordner aus
+FilesWontBeMoved = Dateien werden nicht verschoben
+NoData = Nichts anzuzeigen
+NoInternetConnection = Keine Internetverbindung
+Patient = Bitte Warten...
+Select = Wählen Sie
+Skip = Überspringen
+Skipped = Übersprungen
+SymbolicSkipped = Das Erstellen eines symbolischen Links wurde übersprungen
+Uninstall = Deinstallieren
+'@
diff --git a/LTSC/en-US/Sophia.psd1 b/LTSC/en-US/Sophia.psd1
new file mode 100644
index 00000000..92e87591
--- /dev/null
+++ b/LTSC/en-US/Sophia.psd1
@@ -0,0 +1,78 @@
+ConvertFrom-StringData -StringData @'
+UnsupportedOSBitness = The script supports Windows 10 x64 only
+UnsupportedOSBuild = The script supports Windows 10 2004/20H1 versions and higher
+ControlledFolderAccessDisabled = Controlled folder access disabled
+ScheduledTasks = Scheduled tasks
+ClearFolder = Delete all files in the "{0}" folder?
+FilesBlocked = The following files are being blocked by third-party party apps. Remove them manually and continue
+TempNotEmpty = The "{0}" folder is not empty. Clear it manually
+WindowsFeaturesWindowTitle = Windows features
+FODWindowTitle = Optional features (FODv2)
+EnableHardwareVT = Enable Virtualization in UEFI
+UserShellFolderNotEmpty = Some files left in the "{0}" folder. Move them manually to a new location
+RetrievingDrivesList = Retrieving drives list...
+NewUserShellFolderLocation = New location: "{0}"
+DesktopDriveSelect = Select the drive within the root of which the Desktop folder will be created
+DocumentsDriveSelect = Select the drive within the root of which the Documents folder will be created
+DownloadsDriveSelect = Select the drive within the root of which the Downloads folder will be created
+MusicDriveSelect = Select the drive within the root of which the Music folder will be created
+PicturesDriveSelect = Select the drive within the root of which the Pictures folder will be created
+VideosDriveSelect = Select the drive within the root of which the Videos folder will be created
+DesktopRequest = Would you like to change the location of the Desktop folder?
+DocumentsRequest = Would you like to change the location of the Documents folder?
+DownloadsRequest = Would you like to change the location of the Downloads folder?
+MusicRequest = Would you like to change the location of the Music folder?
+PicturesRequest = Would you like to change the location of the Pictures folder?
+VideosRequest = Would you like to change the location of the Videos folder?
+DesktopFolderSelect = Select a folder for the Desktop folder
+DocumentsFolderSelect = Select a folder for the Documents folder
+DownloadsFolderSelect = Select a folder for the Downloads folder
+MusicFolderSelect = Select a folder for the Music folder
+PicturesFolderSelect = Select a folder for the Pictures folder
+VideosFolderSelect = Select a folder for the Videos folder
+DesktopDefaultFolder = Would you like to change the location of the Desktop folder to the default value?
+DocumentsDefaultFolder = Would you like to change the location of the Documents folder to the default value?
+DownloadsDefaultFolder = Would you like to change the location of the Downloads folder to the default value?
+MusicDefaultFolder = Would you like to change the location of the Music folder to the default value?
+PicturesDefaultFolder = Would you like to change the location of the Pictures folder to the default value?
+VideosDefaultFolder = Would you like to change the location of the Videos folder to the default value?
+GraphicsPerformanceTitle = Graphics performance preference
+GraphicsPerformanceRequest = Would you like to set the graphics performance setting of an app of your choice to "High performance"?
+CleanUpTaskToast = Cleaning up unused Windows files and updates starts in a minute
+CleanUpTaskDescription = Cleaning up unused Windows files and updates using built-in Disk cleanup app
+FolderTaskDescription = The "{0}" folder cleaning
+ControlledFolderAccess = Controlled folder access
+ProtectedFoldersRequest = Would you like to enable Controlled folder access and specify the folder that Microsoft Defender will protect from malicious apps and threats?
+ProtectedFoldersListRemoved = Removed folders
+AppControlledFolderRequest = Would you like to specify an app that is allowed through Controlled Folder access?
+AllowedControlledFolderAppsRemoved = Removed allowed apps
+DefenderTitle = Microsoft Defender
+DefenderExclusionFolderRequest = Would you like to specify a folder to be excluded from Microsoft Defender malware scans?
+DefenderExclusionFoldersListRemoved = Excluded folders removed
+AddDefenderExclusionFileRequest = Would you like to specify a file to be excluded from Microsoft Defender malware scans?
+DefenderExclusionFilesRemoved = Excluded files removed
+EventViewerCustomViewName = Process Creation
+EventViewerCustomViewDescription = Process creation and command-line auditing events
+RestartWarning = Make sure to restart your PC
+ErrorsLine = Line
+ErrorsFile = File
+ErrorsMessage = Errors/Warnings
+Add = Add
+AllFilesFilter = All Files (*.*)|*.*
+Change = Change
+Continue = Continue
+DialogBoxOpening = Displaying the dialog box...
+Disable = Disable
+Enable = Enable
+EXEFilesFilter = *.exe|*.exe|All Files (*.*)|*.*
+FolderSelect = Select a folder
+FilesWontBeMoved = Files will not be moved
+NoData = Nothing to display
+NoInternetConnection = No Internet connection
+Patient = Please wait...
+Select = Select
+Skip = Skip
+Skipped = Skipped
+SymbolicSkipped = Skipped creating a symbolic link
+Uninstall = Uninstall
+'@
diff --git a/LTSC/es-ES/Sophia.psd1 b/LTSC/es-ES/Sophia.psd1
new file mode 100644
index 00000000..0c68a5ca
--- /dev/null
+++ b/LTSC/es-ES/Sophia.psd1
@@ -0,0 +1,78 @@
+ConvertFrom-StringData -StringData @'
+UnsupportedOSBitness = Este script solo soporta Windows 10 x64
+UnsupportedOSBuild = Este script solo soporta Windows 10 2004/20H1 o superior
+ControlledFolderAccessDisabled = Acceso a carpetas controlado desactivado
+ScheduledTasks = Tareas programadas
+ClearFolder = Elimine todos los archivos en la carpeta "{0}"?
+FilesBlocked = Los siguientes archivos están siendo bloqueados por una aplicación de terceros. Elimínelos manualmente y continúe
+TempNotEmpty = La carpeta "{0}" no está vacía. Límpiela manualmente
+WindowsFeaturesWindowTitle = Características de Windows
+FODWindowTitle = Características opcionales (FODv2)
+EnableHardwareVT = Activar virtualización en UEFI
+UserShellFolderNotEmpty = Quedan algunos archivos en la carpeta "{0}". Muévalos manualmente a la nueva ubicación
+RetrievingDrivesList = Recuperando lista de unidades de disco...
+NewUserShellFolderLocation = Nueva ubicación: "{0}"
+DesktopDriveSelect = Selecciona la raíz del disco en la cual se creará la carpeta del Escritorio
+DocumentsDriveSelect = Selecciona la raíz del disco en la cual se creará la carpeta de Documentos
+DownloadsDriveSelect = Selecciona la raíz del disco en la cual se creará la carpeta de Descargas
+MusicDriveSelect = Selecciona la raíz del disco en la cual se creará la carpeta de Música
+PicturesDriveSelect = Selecciona la raíz del disco en la cual se creará la carpeta de Imágenes
+VideosDriveSelect = Selecciona la raíz del disco en la cual se creará la carpeta de Vídeos
+DesktopRequest = Quieres cambiar la ubicación de la carpeta del Escritorio?
+DocumentsRequest = Quieres cambiar la ubicación de la carpeta de Documentos?
+DownloadsRequest = Quieres cambiar la ubicación de la carpeta de Descargas?
+MusicRequest = Quieres cambiar la ubicación de la carpeta de Música?
+PicturesRequest = Quieres cambiar la ubicación de la carpeta de Imágenes?
+VideosRequest = Quieres cambiar la ubicación de la carpeta de Vídeos?
+DesktopFolderSelect = Selecciona una carpeta para la carpeta del Escritorio
+DocumentsFolderSelect = Selecciona una carpeta para la carpeta de Documentos
+DownloadsFolderSelect = Selecciona una carpeta para la carpeta de Descargas
+MusicFolderSelect = Selecciona una carpeta para la carpeta de Música
+PicturesFolderSelect = Selecciona una carpeta para la carpeta de Imágenes
+VideosFolderSelect = Selecciona una carpeta para la carpeta de Vídeos
+DesktopDefaultFolder = Quieres cambiar la ubicación de la carpeta del Escritorio por la de defecto?
+DocumentsDefaultFolder = Quieres cambiar la ubicación de la carpeta de Documentos por la de defecto?
+DownloadsDefaultFolder = Quieres cambiar la ubicación de la carpeta de Descargas por la de defecto?
+MusicDefaultFolder = Quieres cambiar la ubicación de la carpeta de Música por la de defecto?
+PicturesDefaultFolder = Quieres cambiar la ubicación de la carpeta de Imágenes por la de defecto?
+VideosDefaultFolder = Quieres cambiar la ubicación de la carpeta de Vídeos por la de defecto?
+GraphicsPerformanceTitle = Preferencia de rendimiento de gráficos
+GraphicsPerformanceRequest = Quieres establecer el nivel de rendimiento de gráficos a "Alto rendimiento" en alguna aplicación?
+CleanUpTaskToast = Limpiando archivos no usados y actualizaciones de Windows comienza en un minuto
+CleanUpTaskDescription = Limpiando archivos de Windows no usados y actualizaciones usando la aplicación de limpieza de disco incorporada
+FolderTaskDescription = Limpieza de la carpeta "{0}"
+ControlledFolderAccess = Acceso controlado a carpetas
+ProtectedFoldersRequest = Quieres añadir control de acceso a carpeta y especificar que carpeta Microsoft Defender protegerá de aplicaciones maliciosas y amenazas?
+ProtectedFoldersListRemoved = Carpetas eliminadas
+AppControlledFolderRequest = Quieres especificar una aplicación para que sea permitida a través del acceso controlado de carpetas?
+AllowedControlledFolderAppsRemoved = Eliminar aplicaciones permitidas
+DefenderTitle = Microsoft Defender
+DefenderExclusionFolderRequest = Quieres especificar una carpeta para ser excluida por Microsoft Defender?
+DefenderExclusionFoldersListRemoved = Quitadas carpetas excluidas
+AddDefenderExclusionFileRequest = Quieres especificar un archivo para ser excluido por Microsoft Defender?
+DefenderExclusionFilesRemoved = Quitados archivos excluidos
+EventViewerCustomViewName = Creación de procesos
+EventViewerCustomViewDescription = Creación de procesos y eventos de auditoria de línea de comandos
+RestartWarning = Asegúrese de reiniciar su PC
+ErrorsLine = Línea
+ErrorsFile = Archivo
+ErrorsMessage = Errores/Advertencias
+Add = Añadir
+AllFilesFilter = Tutti i file (*.*)|*.*
+Change = Cambiar
+Continue = Continuar
+DialogBoxOpening = Mostrando caja de diálogo...
+Disable = Desactivar
+Enable = Activar
+EXEFilesFilter = *.exe|*.exe|Todos los Archivos (*.*)|*.*
+FolderSelect = Seleccione una carpeta
+FilesWontBeMoved = Los archivos no se moverán
+NoData = Nada que mostrar
+NoInternetConnection = No hay conexión a Internet
+Patient = Por favor espere...
+Select = Seleccionar
+Skip = Omitir
+Skipped = Omitido
+SymbolicSkipped = Se omitió la creación de un enlace simbólico
+Uninstall = Desinstalar
+'@
diff --git a/LTSC/fr-FR/Sophia.psd1 b/LTSC/fr-FR/Sophia.psd1
new file mode 100644
index 00000000..ee3c0c6e
--- /dev/null
+++ b/LTSC/fr-FR/Sophia.psd1
@@ -0,0 +1,78 @@
+ConvertFrom-StringData -StringData @'
+UnsupportedOSBitness = Le script supporte uniquement Windows 10 x64
+UnsupportedOSBuild = Le script supporte les versions Windows 10 2004/20H1 et ultérieures
+ControlledFolderAccessDisabled = Contrôle d'accès aux dossiers désactivé
+ScheduledTasks = Tâches planifiées
+ClearFolder = Supprimer tous les fichiers dans le dossier "{0}"?
+FilesBlocked = Les fichiers suivants sont bloqués par une application tierce `nRetirer les manuellement et continuer
+TempNotEmpty = Le dossier "{0}" n'est pas vide. L'effacer manuellement
+WindowsFeaturesWindowTitle = Fonctionnalités
+FODWindowTitle = Fonctionnalités optionnelles (FODv2)
+EnableHardwareVT = Activer la virtualisation dans UEFI
+UserShellFolderNotEmpty = Certains fichiers laissés dans le dossier "{0}" `nDéplacer les manuellement vers un nouvel emplacement
+RetrievingDrivesList = Récupération de la liste des lecteurs...
+NewUserShellFolderLocation = Nouvel emplacement: "{0}"
+DesktopDriveSelect = Sélectionnez le lecteur à la racine duquel le dossier Bureau sera créé
+DocumentsDriveSelect = Sélectionnez le lecteur à la racine duquel le dossier Documents sera créé
+DownloadsDriveSelect = Sélectionnez le lecteur à la racine duquel le dossier Téléchargements sera créé
+MusicDriveSelect = Sélectionnez le lecteur à la racine duquel le dossier Musique sera créé
+PicturesDriveSelect = Sélectionnez le lecteur à la racine duquel le dossier Images sera créé
+VideosDriveSelect = Sélectionnez le lecteur à la racine duquel le dossier Vidéos sera créé
+DesktopRequest = Souhaitez-vous changer l'emplacement du dossier Bureau?
+DocumentsRequest = Souhaitez-vous changer l'emplacement du dossier Documents?
+DownloadsRequest = Souhaitez-vous changer l'emplacement du dossier Téléchargements?
+MusicRequest = Souhaitez-vous changer l'emplacement du dossier Musique?
+PicturesRequest = Souhaitez-vous changer l'emplacement du dossier Images?
+VideosRequest = Souhaitez-vous changer l'emplacement du dossier Vidéos?
+DesktopFolderSelect = Sélectionner un dossier pour le dossier Bureau
+DocumentsFolderSelect = Sélectionner un dossier pour le dossier Documents
+DownloadsFolderSelect = Sélectionner un dossier pour le dossier Téléchargements
+MusicFolderSelect = Sélectionner un dossier pour le dossier Musique
+PicturesFolderSelect = Sélectionner un dossier pour le dossier Images
+VideosFolderSelect = Sélectionner un dossier pour le dossier Vidéos
+DesktopDefaultFolder = Souhaitez-vous changer l'emplacement du dossier Bureau à la valeur par défaut?
+DocumentsDefaultFolder = Souhaitez-vous changer l'emplacement du dossier Documents à la valeur par défaut?
+DownloadsDefaultFolder = Souhaitez-vous changer l'emplacement du dossier Téléchargements à la valeur par défaut?
+MusicDefaultFolder = Souhaitez-vous changer l'emplacement du dossier Musique à la valeur par défaut?
+PicturesDefaultFolder = Souhaitez-vous changer l'emplacement du dossier Images à la valeur par défaut?
+VideosDefaultFolder = Souhaitez-vous changer l'emplacement du dossier Vidéos à la valeur par défaut?
+GraphicsPerformanceTitle = Préférence de performances graphiques
+GraphicsPerformanceRequest = Souhaitez-vous définir le paramètre de performances graphiques d'une application de votre choix sur "Haute performance"?
+CleanUpTaskToast = Le nettoyage des fichiers Windows inutilisés et des mises à jour débute dans une minute
+CleanUpTaskDescription = Nettoyage des fichiers Windows inutilisés et des mises à jour à l'aide de l'application intégrée pour le nettoyage de disque
+FolderTaskDescription = Nettoyage du dossier "{0}"
+ControlledFolderAccess = Contrôle d'accès aux dossiers
+ProtectedFoldersRequest = Souhaitez-vous activer le contrôle d'accès aux dossiers et spécifier le dossier que Microsoft Defender protégera contre les applications malveillantes et les menaces?
+ProtectedFoldersListRemoved = Dossiers supprimés
+AppControlledFolderRequest = Souhaitez-vous spécifier une application autorisée via le contrôle d'accès aux dossiers?
+AllowedControlledFolderAppsRemoved = Applications autorisées supprimées
+DefenderTitle = Microsoft Defender
+DefenderExclusionFolderRequest = Souhaitez-vous spécifier un dossier à exclure des analyses de logiciels malveillants de Microsoft Defender?
+DefenderExclusionFoldersListRemoved = Dossiers exclus supprimés
+AddDefenderExclusionFileRequest = Souhaitez-vous spécifier un fichier à exclure des analyses de logiciels malveillants de Microsoft Defender?
+DefenderExclusionFilesRemoved = Fichiers exclus supprimés
+EventViewerCustomViewName = Création du processus
+EventViewerCustomViewDescription = Audit des événements de création du processus et de ligne de commande
+RestartWarning = Assurez-vous de redémarrer votre PC
+ErrorsLine = Ligne
+ErrorsFile = Fichier
+ErrorsMessage = Erreurs/Avertissements
+Add = Ajouter
+AllFilesFilter = Tous les Fichiers (*.*)|*.*
+Change = Changer
+Continue = Continuer
+DialogBoxOpening = Afficher la boîte de dialogue...
+Disable = Désactiver
+Enable = Activer
+EXEFilesFilter = *.exe|*.exe|Tous les Fichiers (*.*)|*.*
+FolderSelect = Sélectionner un dossier
+FilesWontBeMoved = Les fichiers ne seront pas déplacés
+NoData = Rien à afficher
+NoInternetConnection = Pas de connexion Internet
+Patient = Veuillez patienter...
+Select = Sélectionner
+Skip = Passer
+Skipped = Passé
+SymbolicSkipped = La création d'un lien symbolique a été ignorée
+Uninstall = Désinstaller
+'@
diff --git a/LTSC/it-IT/Sophia.psd1 b/LTSC/it-IT/Sophia.psd1
new file mode 100644
index 00000000..5fc6d34f
--- /dev/null
+++ b/LTSC/it-IT/Sophia.psd1
@@ -0,0 +1,78 @@
+ConvertFrom-StringData -StringData @'
+UnsupportedOSBitness = Questo script supporta solo Windows 10 x64
+UnsupportedOSBuild = Lo script supporta le versioni di Windows 10 2004/20H1 e successive
+ControlledFolderAccessDisabled = Accesso controllato alle cartelle disabilitato
+ScheduledTasks = Attività pianificate
+ClearFolder = Elimina tutti i file nella cartella "{0}"?
+FilesBlocked = I seguenti file sono bloccati da app di terze parti. Rimuoverli manualmente e continua
+TempNotEmpty = La cartella "{0}" non è vuota. Pulirla manualmente
+WindowsFeaturesWindowTitle = Funzionalità Windows
+FODWindowTitle = Funzionalità facoltative (FODv2)
+EnableHardwareVT = Attiva Virtualizzazione in UEFI
+UserShellFolderNotEmpty = Sono rimasti alcuni file nella cartella "{0}". Spostarli manualmente in una nuova posizione.
+RetrievingDrivesList = Recupero lista delle unità...
+NewUserShellFolderLocation = Nuova posizione: "{0}"
+DesktopDriveSelect = Seleziona l'unità all'interno della radice nella quale verrà creata la cartella Dekstop
+DocumentsDriveSelect = Seleziona l'unità all'interno della radice nella quale verrà creata la cartella Documenti
+DownloadsDriveSelect = Seleziona l'unità all'interno della radice nella quale verrà creata la cartella Download
+MusicDriveSelect = Seleziona l'unità all'interno della radice nella quale verrà creata la cartella Musica
+PicturesDriveSelect = Seleziona l'unità all'interno della radice nella quale verrà creata la cartella Immagini
+VideosDriveSelect = Seleziona l'unità all'interno della radice della quale verrà creata la cartella Video
+DesktopRequest = Desideri cambiare la posizione della cartella Desktop?
+DocumentsRequest = Desideri cambiare la posizione della cartella Documenti?
+DownloadsRequest = Desideri cambiare la posizione della cartella Download?
+MusicRequest = Desideri cambiare la posizione della cartella Musica?
+PicturesRequest = Desideri cambiare la posizione della cartella Immagini?
+VideosRequest = Desideri cambiare la posizione della cartella Video?
+DesktopFolderSelect = Seleziona una cartella per Desktop
+DocumentsFolderSelect = Seleziona una cartella per Documenti
+DownloadsFolderSelect = Seleziona una cartella per Download
+MusicFolderSelect = Seleziona una cartella per Musica
+PicturesFolderSelect = Seleziona una cartella per Immagini
+VideosFolderSelect = Seleziona una cartella per Video
+DesktopDefaultFolder = Desideri modificare la posizione della cartella Desktop sul valore predefinito?
+DocumentsDefaultFolder = Desideri modificare la posizione della cartella Documenti sul valore predefinito?
+DownloadsDefaultFolder = Desideri modificare la posizione della cartella Download sul valore predefinito?
+MusicDefaultFolder = Desideri modificare la posizione della cartella Musica sul valore predefinito?
+PicturesDefaultFolder = Desideri modificare la posizione della cartella Immagini sul valore predefinito?
+VideosDefaultFolder = Desideri modificare la posizione della cartella Video sul valore predefinito?
+GraphicsPerformanceTitle = Preferenze prestazioni della Grafica
+GraphicsPerformanceRequest = Desideri impostare le prestazioni grafiche di un app di tua scelta su "Prestazioni elevate"?
+CleanUpTaskToast = La pulizia dei file e degli aggiornamenti di Windows inutilizzati inizia in un minuto
+CleanUpTaskDescription = Pulizia di file e aggiornamenti di Windows inutilizzati utilizzando l'app di pulizia del disco incorporata
+FolderTaskDescription = Pulizia della cartella "{0}"
+ControlledFolderAccess = Accesso controllato alle cartelle
+ProtectedFoldersRequest = Desideri abilitare l'accesso controllato alle cartelle e specificare la cartella che Microsoft Defender proteggerà dalle app dannose e dalle minacce?
+ProtectedFoldersListRemoved = Cartelle rimosse
+AppControlledFolderRequest = Desideri specificare un'app consentita tramite l'accesso alle cartelle controllate?
+AllowedControlledFolderAppsRemoved = App consentite rimosse
+DefenderTitle = Microsoft Defender
+DefenderExclusionFolderRequest = Desideri specificare una cartella da escludere dalle scansioni del malware di Microsoft Defender?
+DefenderExclusionFoldersListRemoved = Cartelle escluse rimosse
+AddDefenderExclusionFileRequest = Desideri specificare un file da escludere dalle scansioni del malware di Microsoft Defender?
+DefenderExclusionFilesRemoved = File esclusi rimossi
+EventViewerCustomViewName = Creazione del Processo
+EventViewerCustomViewDescription = Creazione di Processi ed Eventi di Controllo dalla riga di comando
+RestartWarning = Assicurati di riavviare il PC
+ErrorsLine = Linea
+ErrorsFile = File
+ErrorsMessage = Errori/Avvisi
+Add = Aggiungi
+AllFilesFilter = Tutti i file (*.*)|*.*
+Change = Cambia
+Continue = Continua
+DialogBoxOpening = Visualizzazione della finestra di dialogo...
+Disable = Disinstalla
+Enable = Abilita
+EXEFilesFilter = *.exe|*.exe|Tutti i file (*.*)|*.*
+FolderSelect = Seleziona una cartella
+FilesWontBeMoved = I file non verranno spostati
+NoData = Nulla da visualizzare
+NoInternetConnection = Nessuna connessione Internet
+Patient = Attendere prego...
+Select = Selezionare
+Skip = Salta
+Skipped = Saltato
+SymbolicSkipped = È stata saltata la creazione di un collegamento simbolico
+Uninstall = Rimuovi
+'@
diff --git a/LTSC/ru-RU/Sophia.psd1 b/LTSC/ru-RU/Sophia.psd1
new file mode 100644
index 00000000..2cb38812
--- /dev/null
+++ b/LTSC/ru-RU/Sophia.psd1
@@ -0,0 +1,78 @@
+ConvertFrom-StringData -StringData @'
+UnsupportedOSBitness = Скрипт поддерживает только Windows 10 x64
+UnsupportedOSBuild = Скрипт поддерживает только Windows 10 версии 2004/20H1 и выше
+ControlledFolderAccessDisabled = Контролируемый доступ к папкам выключен
+ScheduledTasks = Запланированные задачи
+ClearFolder = Удалить все файлы в папке "{0}"?
+FilesBlocked = Следующие файлы блокируются сторонними приложениями. Удалите их вручную и продолжите
+TempNotEmpty = Папка "{0}" не пуста. Очистите ее вручную
+WindowsFeaturesWindowTitle = Компоненты Windows
+FODWindowTitle = Дополнительные компоненты (FODv2)
+EnableHardwareVT = Включите виртуализацию в UEFI
+UserShellFolderNotEmpty = В папке "{0}" остались файлы. Переместите их вручную в новое расположение
+RetrievingDrivesList = Получение списка дисков...
+NewUserShellFolderLocation = Новое расположение: "{0}"
+DesktopDriveSelect = Выберите диск, в корне которого будет создана папка для "Рабочий стол"
+DocumentsDriveSelect = Выберите диск, в корне которого будет создана папка для "Документы"
+DownloadsDriveSelect = Выберите диск, в корне которого будет создана папка для "Загрузки"
+MusicDriveSelect = Выберите диск, в корне которого будет создана папка для "Музыка"
+PicturesDriveSelect = Выберите диск, в корне которого будет создана папка для "Изображения"
+VideosDriveSelect = Выберите диск, в корне которого будет создана папка для "Видео"
+DesktopRequest = Хотите изменить расположение папки "Рабочий стол"?
+DocumentsRequest = Хотите изменить расположение папки "Документы"?
+DownloadsRequest = Хотите изменить расположение папки "Загрузки"?
+MusicRequest = Хотите изменить расположение папки "Музыка"?
+PicturesRequest = Хотите изменить расположение папки "Изображения"?
+VideosRequest = Хотите изменить расположение папки "Видео"?
+DesktopFolderSelect = Выберите папку для "Рабочий стол"
+DocumentsFolderSelect = Выберите папку для "Документы"
+DownloadsFolderSelect = Выберите папку для "Загрузки"
+MusicFolderSelect = Выберите папку для "Музыка"
+PicturesFolderSelect = Выберите папку для "Изображения"
+VideosFolderSelect = Выберите папку для "Видео"
+DesktopDefaultFolder = Хотите изменить расположение папки "Рабочий стол" на значение по умолчанию?
+DocumentsDefaultFolder = Хотите изменить расположение папки "Документы" на значение по умолчанию?
+DownloadsDefaultFolder = Хотите изменить расположение папки "Загрузки" на значение по умолчанию?
+MusicDefaultFolder = Хотите изменить расположение папки "Музыка" на значение по умолчанию?
+PicturesDefaultFolder = Хотите изменить расположение папки "Изображения" на значение по умолчанию?
+VideosDefaultFolder = Хотите изменить расположение папки "Видео" на значение по умолчанию?
+GraphicsPerformanceTitle = Настройка производительности графики
+GraphicsPerformanceRequest = Установить для любого приложения по вашему выбору настройки производительности графики на "Высокая производительность"?
+CleanUpTaskToast = Очистка неиспользуемых файлов и обновлений Windows начнется через минуту
+CleanUpTaskDescription = Очистка неиспользуемых файлов и обновлений Windows, используя встроенную программу Очистка диска
+FolderTaskDescription = Очистка папки "{0}"
+ControlledFolderAccess = Контролируемый доступ к папкам
+ProtectedFoldersRequest = Хотите включить контролируемый доступ к папкам и указать папку, которую Microsoft Defender будет защищать от вредоносных приложений и угроз?
+ProtectedFoldersListRemoved = Удаленные папки
+AppControlledFolderRequest = Указать приложение, которому разрешена работа через контролируемый доступ к папкам
+AllowedControlledFolderAppsRemoved = Удаленные разрешенные приложения
+DefenderTitle = Microsoft Defender
+DefenderExclusionFolderRequest = Указать папку, чтобы исключить ее из списка сканирования Microsoft Defender?
+DefenderExclusionFoldersListRemoved = Исключенные папки удалены
+AddDefenderExclusionFileRequest = Указать файл, чтобы исключить его из списка сканирования Microsoft Defender?
+DefenderExclusionFilesRemoved = Исключенные файлы удалены
+EventViewerCustomViewName = Создание процесса
+EventViewerCustomViewDescription = События содания нового процесса и аудит командной строки
+RestartWarning = Обязательно перезагрузите ваш ПК
+ErrorsLine = Строка
+ErrorsFile = Файл
+ErrorsMessage = Ошибки/предупреждения
+Add = Добавить
+AllFilesFilter = Все файлы (*.*)|*.*
+Change = Изменить
+Continue = Продолжить
+DialogBoxOpening = Диалоговое окно открывается...
+Disable = Отключить
+Enable = Включить
+EXEFilesFilter = *.exe|*.exe|Все файлы (*.*)|*.*
+FolderSelect = Выберите папку
+FilesWontBeMoved = Файлы не будут перенесены
+NoData = Отсутствуют данные
+NoInternetConnection = Отсутствует интернет-соединение
+Patient = Пожалуйста, подождите...
+Select = Выбрать
+Skip = Пропустить
+Skipped = Пропущено
+SymbolicSkipped = Пропущено создание символической ссылки
+Uninstall = Удалить
+'@
diff --git a/LTSC/syspin.exe b/LTSC/syspin.exe
new file mode 100644
index 00000000..772d1476
Binary files /dev/null and b/LTSC/syspin.exe differ
diff --git a/LTSC/tr-TR/Sophia.psd1 b/LTSC/tr-TR/Sophia.psd1
new file mode 100644
index 00000000..fee6df61
--- /dev/null
+++ b/LTSC/tr-TR/Sophia.psd1
@@ -0,0 +1,78 @@
+ConvertFrom-StringData -StringData @'
+UnsupportedOSBitness = Bu betik sadece Windows 10 x64 destekliyor
+UnsupportedOSBuild = Bu betik sadece Windows 10 2004/20H1 sürüm ve üstünü destekliyor
+ControlledFolderAccessDisabled = Kontrollü klasör erişimi devre dışı bırakıldı
+ScheduledTasks = Zamanlanan görevler
+ClearFolder = "{0}" klasöründeki tüm dosyaları silin?
+FilesBlocked = Aşağıdaki dosyalar 3. parti uygulamalar tarafından engelleniyor. `nKendiniz silin ve devam edin
+TempNotEmpty = "{0}" klasörü boş değil. Kendiniz temizleyin
+WindowsFeaturesWindowTitle = Windows özellikleri
+FODWindowTitle = İsteğe bağlı özellikler (FODv2)
+EnableHardwareVT = UEFI'dan sanallaştırmayı aktifleştirin
+UserShellFolderNotEmpty = "{0}" klasöründe bazı dosyalar kaldı. `nKendiniz yeni konuma taşıyın
+RetrievingDrivesList = Sürücü listesi alınıyor...
+NewUserShellFolderLocation = Yeni konum: "{0}"
+DesktopDriveSelect = Masaüstü klasörün oluşturulacağı kök içindeki sürücüyü seçin
+DocumentsDriveSelect = Belgeler klasörün oluşturulacağı kök içindeki sürücüyü seçin
+DownloadsDriveSelect = İndirilenler klasörün oluşturulacağı kök içindeki sürücüyü seçin
+MusicDriveSelect = Müzikler klasörün oluşturulacağı kök içindeki sürücüyü seçin
+PicturesDriveSelect = Resimler klasörün oluşturulacağı kök içindeki sürücüyü seçin
+VideosDriveSelect = Videolar klasörün oluşturulacağı kök içindeki sürücüyü seçin
+DesktopRequest = Masaüstü klasörünün yerini değiştirmek ister misiniz?
+DocumentsRequest = Belgeler klasörünün yerini değiştirmek ister misiniz?
+DownloadsRequest = İndirilenler klasörünün yerini değiştirmek ister misiniz?
+MusicRequest = Müzikler klasörünün yerini değiştirmek ister misiniz?
+PicturesRequest = Resimler klasörünün yerini değiştirmek ister misiniz?
+VideosRequest = Videolar klasörünün yerini değiştirmek ister misiniz?
+DesktopFolderSelect = Masaüstü klasörü için bir klasör seçin.
+DocumentsFolderSelect = Belgeler klasörü için bir klasör seçin.
+DownloadsFolderSelect = İndirilenler klasörü için bir klasör seçin.
+MusicFolderSelect = Müzikler klasörü için bir klasör seçin.
+PicturesFolderSelect = Resimler klasörü için bir klasör seçin.
+VideosFolderSelect = Videolar klasörü için bir klasör seçin.
+DesktopDefaultFolder = Masaüstü klasörünün yerini eski haline getirmek ister misiniz?
+DocumentsDefaultFolder = Belgeler klasörünün yerini eski haline getirmek ister misiniz?
+DownloadsDefaultFolder = İndirilenler klasörünün yerini eski haline getirmek ister misiniz?
+MusicDefaultFolder = Müzikler klasörünün yerini eski haline getirmek ister misiniz?
+PicturesDefaultFolder = Resimler klasörünün yerini eski haline getirmek ister misiniz?
+VideosDefaultFolder = Videolar klasörünün yerini eski haline getirmek ister misiniz?
+GraphicsPerformanceTitle = Grafik performans tercihi
+GraphicsPerformanceRequest = Seçtiğiniz bir uygulamanın grafik performansı ayarını "Yüksek performans" olarak belirlemek ister misiniz?
+CleanUpTaskToast = Kullanılmayan Windows dosyalarının ve güncellemelerin temizlenmesi bir dakika içinde başlar
+CleanUpTaskDescription = Kullanılmayan Windows dosyaları ve güncellemeleri yerleşik Disk Temizleme uygulaması ile temizleniyor
+FolderTaskDescription = "{0}" klasörü temizleniyor
+ControlledFolderAccess = Kontrollü klasör erişimi
+ProtectedFoldersRequest = Kontrollü klasör erişimini etkinleştirmek ve Microsoft Defender'ın kötü amaçlı uygulamalardan ve tehditlerden koruyacağı klasörü belirtmek ister misiniz?
+ProtectedFoldersListRemoved = Silinen klasörler
+AppControlledFolderRequest = Kontrollü Klasör erişimine izin verilen bir uygulama belirtmek ister misiniz?
+AllowedControlledFolderAppsRemoved = Tüm kaldırılan uygulamalar
+DefenderTitle = Microsoft Defender
+DefenderExclusionFolderRequest = Microsoft Defender kötü amaçlı yazılım taramalarının dışında tutulacak bir klasör belirtmek ister misiniz?
+DefenderExclusionFoldersListRemoved = Hariç tutulan klasörler kaldırıldı
+AddDefenderExclusionFileRequest = Microsoft Defender kötü amaçlı yazılım taramalarının dışında bırakılacak bir dosya belirtmek ister misiniz?
+DefenderExclusionFilesRemoved = Hariç tutulan dosyalar kaldırıldı
+EventViewerCustomViewName = Süreç Oluşturma
+EventViewerCustomViewDescription = Süreç oluşturma ve komut satırı denetleme olayları
+RestartWarning = Bilgisayarınızı yeniden başlattığınızdan emin olun
+ErrorsLine = Satır
+ErrorsFile = Dosya
+ErrorsMessage = Hatalar/Uyarılar
+Add = Ekle
+AllFilesFilter = Tüm Dosyalar (*.*)|*.*
+Change = Değiştir
+Continue = Devam et
+DialogBoxOpening = İletişim kutusu görüntüleniyor...
+Disable = Devre dışı bırak
+Enable = Aktif et
+EXEFilesFilter = *.exe|*.exe|Tüm Dosyalar (*.*)|*.*
+FolderSelect = Klasör seç
+FilesWontBeMoved = Dosyalar taşınmayacak
+NoData = Görüntülenecek bir şey yok
+NoInternetConnection = İnternet bağlantısı yok
+Patient = Lütfen bekleyin...
+Select = Seç
+Skip = Atla
+Skipped = Atlandı
+SymbolicSkipped = Sembolik bir bağlantı oluşturma atlandı
+Uninstall = Kaldır
+'@
diff --git a/LTSC/uk-UA/Sophia.psd1 b/LTSC/uk-UA/Sophia.psd1
new file mode 100644
index 00000000..efaa2067
--- /dev/null
+++ b/LTSC/uk-UA/Sophia.psd1
@@ -0,0 +1,78 @@
+ConvertFrom-StringData -StringData @'
+UnsupportedOSBitness = Скрипт підтримує тільки Windows 10 x64
+UnsupportedOSBuild = Скрипт підтримує тільки Windows 10 версії 2004/20H1 та вище
+ControlledFolderAccessDisabled = Контрольований доступ до папок вимкнений
+ScheduledTasks = Заплановані задачі
+ClearFolder = Видаліть всі файли у папці "{0}"?
+FilesBlocked = Наступні файли блокуються сторонніми програмами\nВидаліть їх вручну та продовжуйте
+TempNotEmpty = Папка "{0}" не порожня. Очистіть її вручну
+WindowsFeaturesWindowTitle = Компоненти Windows
+FODWindowTitle = Додаткові компоненти (FODv2)
+EnableHardwareVT = Увімкніть віртуалізацію в UEFI
+UserShellFolderNotEmpty = У папці "{0}" залишились файли. Перемістіть їх вручну у нове розташування
+RetrievingDrivesList = Отримання списку дисків...
+NewUserShellFolderLocation = Нове розташування: "{0}"
+DesktopDriveSelect = Виберіть диск, в корні якого буде створена папка для "Робочий стіл"
+DocumentsDriveSelect = Виберіть диск, в корні якого буде створена папка для "Документи"
+DownloadsDriveSelect = Виберіть диск, в корні якого буде створена папка для "Завантаження"
+MusicDriveSelect = Виберіть диск, в корні якого буде створена папка для "Музика"
+PicturesDriveSelect = Виберіть диск, в корні якого буде створена папка для "Зображения"
+VideosDriveSelect = Виберіть диск, в корні якого буде створена папка для "Відео"
+DesktopRequest = Хочете змінити розташування папки "Робочий стіл"?
+DocumentsRequest = Хочете змінити розташування папки "Документи"?
+DownloadsRequest = Хочете змінити розташування папки "Завантаження"?
+MusicRequest = Хочете змінити розташування папки "Музика"?
+PicturesRequest = Хочете змінити розташування папки "Зображения"?
+VideosRequest = Хочете змінити розташування папки "Відео"?
+DesktopFolderSelect = Виберіть папку для "Робочий стіл"
+DocumentsFolderSelect = Виберіть папку для "Документи"
+DownloadsFolderSelect = Виберіть папку для "Завантаження"
+MusicFolderSelect = Виберіть папку для "Музика"
+PicturesFolderSelect = Виберіть папку для "Зображения"
+VideosFolderSelect = Виберіть папку для "Відео"
+DesktopDefaultFolder = Хочете змінити розташування папки "Робочий стіл" на значення за замовчуванням?
+DocumentsDefaultFolder = Хочете змінити розташування папки "Документи" на значення за замовчуванням?
+DownloadsDefaultFolder = Хочете змінити розташування папки "Завантаження" на значення за замовчуванням?
+MusicDefaultFolder = Хочете змінити розташування папки "Музика" на значення за замовчуванням?
+PicturesDefaultFolder = Хочете змінити розташування папки "Зображения" на значення за замовчуванням?
+VideosDefaultFolder = Хочете змінити розташування папки "Відео" на значення за замовчуванням?
+GraphicsPerformanceTitle = Налаштування продуктивності графіки
+GraphicsPerformanceRequest = Встановити для будь-якої програми за вашим вибором налаштування продуктивності графіки на "Висока продуктивність"?
+CleanUpTaskToast = Очищення зайвих файлів і оновлень Windows почнеться через хвилину
+CleanUpTaskDescription = Очищення зайвих файлів і оновлень Windows, використовуючи вбудовану програму очищення диска
+FolderTaskDescription = Очищення папки "{0}"
+ControlledFolderAccess = Контрольований доступ до папок
+ProtectedFoldersRequest = Бажаєте увімкнути контрольований доступ до папок і вказати папку, яку Microsoft Defender буде захищати від шкідливих додатків і загроз?
+ProtectedFoldersListRemoved = Видалення папки
+AppControlledFolderRequest = Вказати додаток, якому дозволена робота через контрольований доступ до папок
+AllowedControlledFolderAppsRemoved = Видалені дозволені додатки
+DefenderTitle = Microsoft Defender
+DefenderExclusionFolderRequest = Вказати папку, щоб виключити її зі списку сканування Microsoft Defender?
+DefenderExclusionFoldersListRemoved = Виключені папки видалені
+AddDefenderExclusionFileRequest = Вказати файл, щоб виключити його зі списку сканування Microsoft Defender?
+DefenderExclusionFilesRemoved = Виключені файли видалені
+EventViewerCustomViewName = Створення процесу
+EventViewerCustomViewDescription = Події створення нового процесу і аудит командного рядка
+RestartWarning = Обов'язково перезавантажте ваш ПК
+ErrorsLine = Рядок
+ErrorsFile = Файл
+ErrorsMessage = Помилки/попередження
+Add = Додати
+AllFilesFilter = Усі файли (*.*)|*.*
+Change = Змінити
+Continue = Продовжити
+DialogBoxOpening = Діалогове вікно відкривається...
+Disable = Вимкнути
+Enable = Увімкнути
+EXEFilesFilter = *.exe|*.exe|Усі файли (*.*)|*.*
+FolderSelect = Виберіть папку
+FilesWontBeMoved = Файли не будуть перенесені
+NoData = Відсутні дані
+NoInternetConnection = Відсутнє інтернет-з'єднання
+Patient = Будь ласка, зачекайте...
+Select = Вибрати
+Skip = Пропустити
+Skipped = Пропущено
+SymbolicSkipped = Пропущено створення символічного посилання
+Uninstall = Видалити
+'@