Windows 10 Sophia Script is a set of PowerShell functions that help you to fine-tune the configuration of Windows 10. A little over a year ago, I released the 4.0 script version for automating the configuration of Windows 10. Recently, I rewrote the Windows 10 Sophia Script from scratch into a module for one-time use.

There were three main complaints about the previous version:

  1. Nobody wanted to dig into the 3,500 lines of code and comment out/uncomment this or that section so that it would not be run in the future.
  2. If it were necessary to revert changes to the default values, no one could figure out exactly what to do.
  3. It was impossible to translate commands into another language without editing the code. Starting from the 5.1 version, localization files have been moved to separate files, which will facilitate the translation process.
Windows 10 Sophia Script—Packages to uninstall

Windows 10 Sophia Script—Packages to uninstall

Now the script comprises two files: the module itself and the preset file for it, excluding the localization files. The module is divided into about 270 functions, both for making changes and for reverting them.

The preset file lists comments sections for each function (with a detailed description of each), and comments out the line with the functions using the # char so that this function won't be executed, or, conversely, removes the # sign in front of it, so that the function will be executed. Put another way, almost every function has a revert function to return to its default state.

The advantage is that once you have created your script correctly, you can use it repeatedly.

The Windows 10 Sophia Script should ideally be run on new installations.

Supported Windows 10 versions ^

The Windows 10 Sophia Script only supports the current versions of Windows 10: 2004 (20H1) and 2009 (20H2), x64, since they are essentially the same version. Perhaps, a little later, I'll release a version for LTSC (1809), since this version of Windows 10 is quite popular. For now, for other versions, you can use the previous version of the 4.x script.

Core features ^

  • Set up privacy and telemetry.
  • Turn off diagnostics that track scheduled tasks.
  • Set up UI and personalization.
  • Uninstall OneDrive correctly.
  • Interactive prompts.
  • Change the %TEMP% environment variable path to %SystemDrive%\Temp.
  • Change location of the user folders programmatically (without moving user files) within the interactive menu, using the up/down arrows and the Enter key to make selections.
    • Desktop
    • Documents
    • Downloads
    • Music
    • Pictures
    • Videos
  • Uninstall UWP apps from all accounts with the popup form written in WPF. The system packages are excluded from uninstalling.
  • Disable Windows features.
  • Install and set up WSL.
  • Remove Windows capabilities, with the popup form written in WPF.
  • Create a Windows cleanup task in the Task Scheduler
    • A toast notification will pop up a minute before the task starts.
  • Create tasks in the Task Scheduler to clear.
    • %SystemRoot%\SoftwareDistribution\Download
    • %TEMP%
  • Unpin all Start menu tiles.
  • Pin shortcuts to the Start menu using syspin.exe.
    • Three shortcuts are preconfigured to be pinned: Control Panel, old-style Devices and Printers, and the command prompt.
  • Turn on controlled folder access and add protected folders;
  • Exclude folders from Microsoft Defender Antivirus scanning;
  • Exclude files from Microsoft Defender Antivirus scanning;
  • Refresh desktop icons, environment variables, and taskbar without restarting File Explorer.
  • Set up Windows 10 security.
  • Many more File Explorer and context menu tweaks.

A complete list of functions can be found in the preset file.

Screenshots ^

Changing the location of the user folders to any drives root using arrows

Changing the location of the user folders to any drives root using arrows

Disabling certain Feature On Demand v2 FODv2 capabilities

Disabling certain Feature On Demand v2 FODv2 capabilities

Sophia Script video demonstration ^

Windows 10 Sophia Script in Action

Cleaning up unused Windows files and updates in action

Subscribe to 4sysops newsletter!

Usage ^

  • Download the up-to-date version.
  • Look through the preset file to configure functions that you want to run.
    • Comment out a function with the # char if you don't want it to be run.
    • Uncomment a function by removing the # char if you want it to be run.
  • Set the execution policy to be able to run scripts only in the current PowerShell session.Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force
  • Type .\Sophia.psd1
  • Press Enter

The scripts ^

<#
	.SYNOPSIS
	"Windows 10 Sophia Script" is a set of functions for Windows 10 fine-tuning and automating the routine tasks

	Version: v5.1.1
	Date: 09.10.2020
	Copyright (c) 2020 farag & oZ-Zo

	Thanks to all http://forum.ru-board.com members involved

	.DESCRIPTION
	Supported Windows 10 versions: 2004 (20H1)/2009 (20H2), 19041/19042, Home/Pro/Enterprise, x64

	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 "CreateCleanUpTask" function
	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 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
	http://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/
	    
[PowerShell Script] Setup Windows 10 from PowerShell
.LINK https://github.com/farag2/Windows-10-Sophia-Script #> #region Check function Check { Set-StrictMode -Version Latest # Сlear the $Error variable $Global:Error.Clear() # Detect the OS bitness switch ([Environment]::Is64BitOperatingSystem) { $false { Write-Warning -Message $Localization.UnsupportedOSBitness break } } # 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 Check # Create a restore point function CreateRestorePoint { if (-not (Get-ComputerRestorePoint)) { Enable-ComputerRestore -Drive $env:SystemDrive } # Set system restore point creation frequency to 5 minutes New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -Name SystemRestorePointCreationFrequency -PropertyType DWord -Value 5 -Force Checkpoint-Computer -Description "Windows 10 Sophia Script.ps1" -RestorePointType MODIFY_SETTINGS # Revert the System Restore checkpoint creation frequency to 1440 minutes New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -Name SystemRestorePointCreationFrequency -PropertyType DWord -Value 1440 -Force } #region Privacy & Telemetry # Disable the "Connected User Experiences and Telemetry" service (DiagTrack) function DisableTelemetryServices { Get-Service -Name DiagTrack | Stop-Service -Force Get-Service -Name DiagTrack | Set-Service -StartupType Disabled } # Enable the "Connected User Experiences and Telemetry" service (DiagTrack) function EnableTelemetryServices { Get-Service -Name DiagTrack | Set-Service -StartupType Automatic Get-Service -Name DiagTrack | Start-Service } # Set the OS level of diagnostic data gathering to "Minimum" function SetMinimalDiagnosticDataLevel { if (Get-WindowsEdition -Online | Where-Object -FilterScript {$_.Edition -like "Enterprise*" -or $_.Edition -eq "Education"}) { # "Security" New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 0 -Force } else { # "Basic" New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 1 -Force } } # Set the default OS level of diagnostic data gathering function SetDefaultDiagnosticDataLevel { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 3 -Force } # Turn off Windows Error Reporting for the current user function DisableWindowsErrorReporting { 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 } } # Turn on Windows Error Reporting for the current user function EnableWindowsErrorReporting { Get-ScheduledTask -TaskName QueueReporting | Enable-ScheduledTask Remove-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\Windows Error Reporting" -Name Disabled -Force -ErrorAction SilentlyContinue } # Change Windows feedback frequency to "Never" for the current user function DisableWindowsFeedback { 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 } # Change Windows Feedback frequency to "Automatically" for the current user function EnableWindowsFeedback { Remove-Item -Path HKCU:\SOFTWARE\Microsoft\Siuf\Rules -Force -ErrorAction SilentlyContinue } # Turn off diagnostics tracking scheduled tasks function DisableScheduledTasks { $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 "Proxy", # If the user has consented to participate in the Windows Customer Experience Improvement Program, this job collects and sends usage data to Microsoft "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 "UsbCeip", # The Windows Disk Diagnostic reports general disk and system information to Microsoft for users participating in the Customer Experience Program "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 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 function EnableScheduledTasks { $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 "Proxy", # If the user has consented to participate in the Windows Customer Experience Improvement Program, this job collects and sends usage data to Microsoft "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 "UsbCeip", # The Windows Disk Diagnostic reports general disk and system information to Microsoft for users participating in the Customer Experience Program "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 if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2) { # HelloFace $ScheduledTaskList += "FODCleanupTask" } Get-ScheduledTask -TaskName $ScheduledTaskList | Enable-ScheduledTask } # Do not use sign-in info to automatically finish setting up device and reopen apps after an update or restart (current user only) function DisableSigninInfo { $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 } # Use sign-in info to automatically finish setting up device and reopen apps after an update or restart (current user only) function EnableSigninInfo { $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 } # Do not let websites provide locally relevant content by accessing language list (current user only) function DisableLanguageListAccess { New-ItemProperty -Path "HKCU:\Control Panel\International\User Profile" -Name HttpAcceptLanguageOptOut -PropertyType DWord -Value 1 -Force } # Let websites provide locally relevant content by accessing language list (current user only) function EnableLanguageListAccess { Remove-ItemProperty -Path "HKCU:\Control Panel\International\User Profile" -Name HttpAcceptLanguageOptOut -Force -ErrorAction SilentlyContinue } # Do not allow apps to use advertising ID (current user only) function DisableAdvertisingID { 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 } # Allow apps to use advertising ID (current user only) function EnableAdvertisingID { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo -Name Enabled -PropertyType DWord -Value 1 -Force } # Do not let apps on other devices open and message apps on this device, and vice versa (current user only) function DisableShareAcrossDevices { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\CDP -Name RomeSdkChannelUserAuthzPolicy -PropertyType DWord -Value 0 -Force } # Let apps on other devices open and message apps on this device, and vice versa (current user only) function EnableShareAcrossDevices { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\CDP -Name RomeSdkChannelUserAuthzPolicy -PropertyType DWord -Value 1 -Force } # Do not show the Windows welcome experiences after updates and occasionally when I sign in to highlight what's new and suggested (current user only) function DisableWindowsWelcomeExperience { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-310093Enabled -PropertyType DWord -Value 0 -Force } # Show the Windows welcome experiences after updates and occasionally when I sign in to highlight what's new and suggested (current user only) function EnableWindowsWelcomeExperience { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-310093Enabled -PropertyType DWord -Value 1 -Force } # Get tip, trick, and suggestions as you use Windows (current user only) function EnableWindowsTips { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338389Enabled -PropertyType DWord -Value 1 -Force } # Do not get tip, trick, and suggestions as you use Windows (current user only) function DisableWindowsTips { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338389Enabled -PropertyType DWord -Value 0 -Force } # Do not show suggested content in the Settings app (current user only) function DisableSuggestedContent { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338393Enabled -PropertyType DWord -Value 0 -Force New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-353694Enabled -PropertyType DWord -Value 0 -Force New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-353696Enabled -PropertyType DWord -Value 0 -Force } # Show suggested content in the Settings app (current user only) function EnableSuggestedContent { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338393Enabled -PropertyType DWord -Value 1 -Force New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-353694Enabled -PropertyType DWord -Value 1 -Force New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-353696Enabled -PropertyType DWord -Value 1 -Force } # Turn off automatic installing suggested apps (current user only) function DisableAppsSilentInstalling { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SilentInstalledAppsEnabled -PropertyType DWord -Value 0 -Force } # Turn on automatic installing suggested apps (current user only) function EnableAppsSilentInstalling { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SilentInstalledAppsEnabled -PropertyType DWord -Value 1 -Force } # Do not suggest ways I can finish setting up my device to get the most out of Windows (current user only) function DisableWhatsNewInWindows { if (-not (Test-Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\UserProfileEngagement)) { New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\UserProfileEngagement -Force } New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\UserProfileEngagement -Name ScoobeSystemSettingEnabled -PropertyType DWord -Value 0 -Force } # Suggest ways I can finish setting up my device to get the most out of Windows function EnableWhatsNewInWindows { if (-not (Test-Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\UserProfileEngagement)) { New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\UserProfileEngagement -Force } New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\UserProfileEngagement -Name ScoobeSystemSettingEnabled -PropertyType DWord -Value 1 -Force } # Do not offer tailored experiences based on the diagnostic data setting (current user only) function DisableTailoredExperiences { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Privacy -Name TailoredExperiencesWithDiagnosticDataEnabled -PropertyType DWord -Value 0 -Force } # Offer tailored experiences based on the diagnostic data setting function EnableTailoredExperiences { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Privacy -Name TailoredExperiencesWithDiagnosticDataEnabled -PropertyType DWord -Value 1 -Force } # Disable Bing search in the Start Menu (for the USA only) function DisableBingSearch { if ((Get-WinHomeLocation).GeoId -eq 244) { if (-not (Test-Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer)) { New-Item -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Force } New-ItemProperty -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name DisableSearchBoxSuggestions -PropertyType DWord -Value 1 -Force } } # Enable Bing search in the Start Menu only (for the USA only) function EnableBingSearch { if ((Get-WinHomeLocation).GeoId -eq 244) { Remove-ItemProperty -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name DisableSearchBoxSuggestions -Force -ErrorAction SilentlyContinue } } #endregion Privacy & Telemetry #region UI & Personalization # Show "This PC" on Desktop (current user only) function ShowThisPC { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -PropertyType DWord -Value 0 -Force } # Do not show "This PC" on Desktop (current user only) function HideThisPC { Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -Force -ErrorAction SilentlyContinue } # Do not use check boxes to select items (current user only) function DisableCheckBoxes { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name AutoCheckSelect -PropertyType DWord -Value 0 -Force } # Use check boxes to select items (current user only) function EnableCheckBoxes { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name AutoCheckSelect -PropertyType DWord -Value 1 -Force } # Show hidden files, folders, and drives (current user only) function ShowHiddenItems { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name Hidden -PropertyType DWord -Value 1 -Force } # Do not show hidden files, folders, and drives (current user only) function HideHiddenItems { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name Hidden -PropertyType DWord -Value 2 -Force } # Show file name extensions (current user only) function ShowFileExtensions { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideFileExt -PropertyType DWord -Value 0 -Force } # Do not show file name extensions (current user only) function HideFileExtensions { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideFileExt -PropertyType DWord -Value 1 -Force } # Do not hide folder merge conflicts (current user only) function ShowMergeConflicts { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideMergeConflicts -PropertyType DWord -Value 1 -Force } # Hide folder merge conflicts (current user only) function HideMergeConflicts { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideMergeConflicts -PropertyType DWord -Value 0 -Force } # Open File Explorer to: "This PC" (current user only) function OpenFileExplorerToThisPC { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name LaunchTo -PropertyType DWord -Value 1 -Force } # Open File Explorer to: "Quick access" (current user only) function OpenFileExplorerToQuickAccess { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name LaunchTo -PropertyType DWord -Value 2 -Force } # Do not show Cortana button on the taskbar (current user only) function HideCortanaButton { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowCortanaButton -PropertyType DWord -Value 0 -Force } # Show Cortana button on the taskbar (current user only) function ShowCortanaButton { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowCortanaButton -PropertyType DWord -Value 1 -Force } # Do not show sync provider notification within File Explorer (current user only) function HideOneDriveFileExplorerAd { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSyncProviderNotifications -PropertyType DWord -Value 0 -Force } # Show sync provider notification within File Explorer (current user only) function ShowOneDriveFileExplorerAd { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSyncProviderNotifications -PropertyType DWord -Value 1 -Force } # Do not show Task View button on the taskbar (current user only) function HideTaskViewButton { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowTaskViewButton -PropertyType DWord -Value 0 -Force } # Show Task View button on the taskbar (current user only) function ShowTaskViewButton { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowTaskViewButton -PropertyType DWord -Value 1 -Force } # Do not show People button on the taskbar (current user only) function HidePeopleTaskbar { 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) function ShowPeopleTaskbar { 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 } # Show seconds on the taskbar clock (current user only) function ShowSecondsInSystemClock { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSecondsInSystemClock -PropertyType DWord -Value 1 -Force } # Do not show seconds on the taskbar clock (current user only) function HideSecondsInSystemClock { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSecondsInSystemClock -PropertyType DWord -Value 0 -Force } # Do not show when snapping a window, what can be attached next to it (current user only) function DisableSnapAssist { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SnapAssist -PropertyType DWord -Value 0 -Force } # Show when snapping a window, what can be attached next to it (current user only) function EnableSnapAssist { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SnapAssist -PropertyType DWord -Value 1 -Force } # Always open the file transfer dialog box in the detailed mode (current user only) function FileTransferDialogDetailed { 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 } # Always open the file transfer dialog box in the compact mode (current user only) function FileTransferDialogCompact { 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 } # Show the ribbon expanded in File Explorer (current user only) function FileExplorerRibbonExpanded { 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 } # Do not show the ribbon expanded in File Explorer (current user only) function FileExplorerRibbonMinimized { 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 } # Display recycle bin files delete confirmation function EnableRecycleBinDeleteConfirmation { $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 $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 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 PostMessageW(hWnd, Msg, UIntPtr, IntPtr.Zero); } "@ } if (-not ("WinAPI.UpdateDesktop" -as [type])) { Add-Type @UpdateDesktop } # Send F5 pressing simulation to refresh the desktop [WinAPI.UpdateDesktop]::PostMessage() } # Do not display recycle bin files delete confirmation function DisableRecycleBinDeleteConfirmation { $ShellState = Get-ItemPropertyValue -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShellState $ShellState[4] = 55 New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShellState -PropertyType Binary -Value $ShellState -Force $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 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 PostMessageW(hWnd, Msg, UIntPtr, IntPtr.Zero); } "@ } if (-not ("WinAPI.UpdateDesktop" -as [type])) { Add-Type @UpdateDesktop } # Send F5 pressing simulation to refresh the desktop [WinAPI.UpdateDesktop]::PostMessage() } # Hide the "3D Objects" folder from "This PC" and "Quick access" (current user only) function Hide3DObjects { 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 # 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 } } } # Show the "3D Objects" folder from "This PC" and "Quick access" (current user only) function Show3DObjects { 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 } } } # Do not show frequently used folders in "Quick access" (current user only) function HideQuickAccessFrequentFolders { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShowFrequent -PropertyType DWord -Value 0 -Force } # Show frequently used folders in "Quick access" (current user only) function ShowQuickAccessFrequentFolders { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShowFrequent -PropertyType DWord -Value 1 -Force } # Do not show recently used files in Quick access (current user only) function HideQuickAccessRecentFiles { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShowRecent -PropertyType DWord -Value 0 -Force } # Show recently used files in Quick access (current user only) function ShowQuickAccessShowRecentFiles { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name ShowRecent -PropertyType DWord -Value 1 -Force } # Hide the search box or the search icon from the taskbar (current user only) function HideTaskbarSearch { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search -Name SearchboxTaskbarMode -PropertyType DWord -Value 0 -Force } # Show the search box from the taskbar (current user only) function ShowTaskbarSearch { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search -Name SearchboxTaskbarMode -PropertyType DWord -Value 2 -Force } # Do not show the "Windows Ink Workspace" button on the taskbar (current user only) function HideWindowsInkWorkspace { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\PenWorkspace -Name PenWorkspaceButtonDesiredVisibility -PropertyType DWord -Value 0 -Force } # Show the "Windows Ink Workspace" button in taskbar (current user only) function ShowWindowsInkWorkspace { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\PenWorkspace -Name PenWorkspaceButtonDesiredVisibility -PropertyType DWord -Value 1 -Force } # Always show all icons in the notification area (current user only) function ShowTrayIcons { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name EnableAutoTray -PropertyType DWord -Value 0 -Force } # Do not show all icons in the notification area (current user only) function HideTrayIcons { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name EnableAutoTray -PropertyType DWord -Value 1 -Force } # Unpin "Microsoft Edge" and "Microsoft Store" from the taskbar (current user only) function UnpinTaskbarEdgeStore { $Signature = @{ Namespace = "WinAPI" Name = "GetStr" Language = "CSharp" MemberDefinition = @" // https://github.com/Disassembler0/Win10-Initial-Setup-Script/issues/8#issue-227159084 [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("user32.dll", CharSet = CharSet.Auto)] internal static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax); public static string GetString(uint strId) { IntPtr intPtr = GetModuleHandle("shell32.dll"); StringBuilder sb = new StringBuilder(255); LoadString(intPtr, strId, sb, sb.Capacity); return sb.ToString(); } "@ } if (-not ("WinAPI.GetStr" -as [type])) { Add-Type @Signature -Using System.Text } # Extract the "Unpin from taskbar" string from shell32.dll $LocalizedString = [WinAPI.GetStr]::GetString(5387) $Apps = (New-Object -ComObject Shell.Application).NameSpace("shell:::{4234d49b-0245-4df3-b780-3893943456e1}").Items() $Apps | Where-Object -FilterScript {$_.Path -eq "MSEdge"} | ForEach-Object -Process {$_.Verbs() | Where-Object -FilterScript {$_.Name -eq $LocalizedString} | ForEach-Object -Process {$_.DoIt()}} $Apps | Where-Object -FilterScript {$_.Name -eq "Microsoft Store"} | ForEach-Object -Process {$_.Verbs() | Where-Object -FilterScript {$_.Name -eq $LocalizedString} | ForEach-Object -Process {$_.DoIt()}} } # View the Control Panel icons by: large icons (current user only) function ControlPanelLargeIcons { 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 } # View the Control Panel icons by: category (current user only) function ControlPanelCategoryIcons { 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 } # Set the Windows mode color scheme to the light (current user only) function WindowsColorSchemeLight { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name SystemUsesLightTheme -PropertyType DWord -Value 1 -Force } # Set the Windows mode color scheme to the dark (current user only) function WindowsColorSchemeDark { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name SystemUsesLightTheme -PropertyType DWord -Value 0 -Force } # Set the default app mode color scheme to the light (current user only) function AppModeLight { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -PropertyType DWord -Value 1 -Force } # Set the default app mode color scheme to the dark (current user only) function AppModeDark { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize -Name AppsUseLightTheme -PropertyType DWord -Value 0 -Force } # Do not show the "New App Installed" indicator function DisableNewAppInstalledNotification { 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 the "New App Installed" indicator function EnableNewAppInstalledNotification { 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 } # Do not show user first sign-in animation after the upgrade function HideFirstSigninAnimation { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableFirstLogonAnimation -PropertyType DWord -Value 0 -Force } # Show user first sign-in animation the upgrade function ShowFirstSigninAnimation { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableFirstLogonAnimation -PropertyType DWord -Value 1 -Force } # Set the quality factor of the JPEG desktop wallpapers to maximum (current user only) function JPEGWallpapersQualityMax { New-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name JPEGImportQuality -PropertyType DWord -Value 100 -Force } # Set the quality factor of the JPEG desktop wallpapers to default (current user only) function JPEGWallpapersQualityDefault { Remove-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name JPEGImportQuality -Force -ErrorAction SilentlyContinue } # Start Task Manager in expanded mode (current user only) function TaskManagerWindowExpanded { $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 } # Start Task Manager in compact mode (current user only) function TaskManagerWindowCompact { $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] = 1 New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\TaskManager -Name Preferences -PropertyType Binary -Value $Preferences.Preferences -Force } # Show a notification when your PC requires a restart to finish updating function ShowRestartNotification { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name RestartNotificationsAllowed2 -PropertyType DWord -Value 1 -Force } # Do not show a notification when your PC requires a restart to finish updating function HideRestartNotification { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name RestartNotificationsAllowed2 -PropertyType DWord -Value 0 -Force } # Do not add the "- Shortcut" suffix to the file name of created shortcuts (current user only) function DisableShortcutsSuffix { 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 } # Add the "- Shortcut" suffix to the file name of created shortcuts (current user only) function EnableShortcutsSuffix { Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\NamingTemplates -Name ShortcutNameTemplate -Force -ErrorAction SilentlyContinue } # Use the PrtScn button to open screen snipping (current user only) function EnablePrtScnSnippingTool { New-ItemProperty -Path "HKCU:\Control Panel\Keyboard" -Name PrintScreenKeyForSnippingEnabled -PropertyType DWord -Value 1 -Force } # Do not use the PrtScn button to open screen snipping (current user only) function DisablePrtScnSnippingTool { New-ItemProperty -Path "HKCU:\Control Panel\Keyboard" -Name PrintScreenKeyForSnippingEnabled -PropertyType DWord -Value 0 -Force } #endregion UI & Personalization #region OneDrive # Uninstall OneDrive function UninstallOneDrive { [string]$UninstallString = Get-Package -Name "Microsoft OneDrive" -ProviderName Programs -ErrorAction Ignore | ForEach-Object -Process {$_.Meta.Attributes["UninstallString"]} if ($UninstallString) { Write-Verbose -Message $Localization.OneDriveUninstalling -Verbose Stop-Process -Name OneDrive -Force -ErrorAction Ignore Stop-Process -Name OneDriveSetup -Force -ErrorAction Ignore Stop-Process -Name FileCoAuth -Force -ErrorAction Ignore # Getting link to the OneDriveSetup.exe and its' argument(s) [string[]]$OneDriveSetup = ($UninstallString -Replace("\s*/",",/")).Split(",").Trim() if ($OneDriveSetup.Count -eq 2) { Start-Process -FilePath $OneDriveSetup[0] -ArgumentList $OneDriveSetup[1..1] -Wait } else { Start-Process -FilePath $OneDriveSetup[0] -ArgumentList $OneDriveSetup[1..2] -Wait } # Getting the OneDrive user folder path $OneDriveUserFolder = Get-ItemPropertyValue -Path HKCU:\Environment -Name OneDrive if ((Get-ChildItem -Path $OneDriveUserFolder | Measure-Object).Count -eq 0) { Remove-Item -Path $OneDriveUserFolder -Recurse -Force } else { $Message = Invoke-Command -ScriptBlock ([ScriptBlock]::Create($Localization.OneDriveNotEmptyFolder)) Write-Error -Message $Message -ErrorAction SilentlyContinue Invoke-Item -Path $OneDriveUserFolder } Remove-ItemProperty -Path HKCU:\Environment -Name OneDrive, OneDriveConsumer -Force -ErrorAction Ignore Remove-Item -Path HKCU:\SOFTWARE\Microsoft\OneDrive -Recurse -Force -ErrorAction Ignore Remove-Item -Path HKLM:\SOFTWARE\WOW6432Node\Microsoft\OneDrive -Recurse -Force -ErrorAction Ignore Remove-Item -Path "$env:ProgramData\Microsoft OneDrive" -Recurse -Force -ErrorAction Ignore Remove-Item -Path $env:SystemDrive\OneDriveTemp -Recurse -Force -ErrorAction Ignore Unregister-ScheduledTask -TaskName *OneDrive* -Confirm:$false # Getting the OneDrive folder path $OneDriveFolder = Split-Path -Path (Split-Path -Path $OneDriveSetup[0] -Parent) # Save all opened folders in order to restore them after File Explorer restarting Clear-Variable -Name OpenedFolders -Force -ErrorAction Ignore $OpenedFolders = {(New-Object -ComObject Shell.Application).Windows() | ForEach-Object -Process {$_.Document.Folder.Self.Path}}.Invoke() # Terminate File Explorer process TASKKILL /F /IM explorer.exe # Attempt to unregister FileSyncShell64.dll and remove $FileSyncShell64dlls = Get-ChildItem -Path "$OneDriveFolder\*\amd64\FileSyncShell64.dll" -Force foreach ($FileSyncShell64dll in $FileSyncShell64dlls.FullName) { Start-Process -FilePath regsvr32.exe -ArgumentList "/u /s $FileSyncShell64dll" -Wait Remove-Item -Path $FileSyncShell64dll -Force -ErrorAction Ignore if (Test-Path -Path $FileSyncShell64dll) { $Message = Invoke-Command -ScriptBlock ([ScriptBlock]::Create($Localization.OneDriveFileSyncShell64dllBlocked)) Write-Error -Message $Message -ErrorAction SilentlyContinue } } # Restoring closed folders Start-Process -FilePath explorer foreach ($OpenedFolder in $OpenedFolders) { if (Test-Path -Path $OpenedFolder) { Invoke-Item -Path $OpenedFolder } } Remove-Item -Path $OneDriveFolder -Recurse -Force -ErrorAction Ignore Remove-Item -Path $env:LOCALAPPDATA\OneDrive -Recurse -Force -ErrorAction Ignore Remove-Item -Path $env:LOCALAPPDATA\Microsoft\OneDrive -Recurse -Force -ErrorAction Ignore Remove-Item -Path "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\OneDrive.lnk" -Force -ErrorAction Ignore } } # Install OneDrive (current user only) function InstallOneDrive { $OneDrive = Get-Package -Name "Microsoft OneDrive" -ProviderName Programs -Force -ErrorAction Ignore if (-not $OneDrive) { if (Test-Path -Path $env:SystemRoot\SysWOW64\OneDriveSetup.exe) { Write-Verbose -Message $Localization.OneDriveInstalling -Verbose Start-Process -FilePath $env:SystemRoot\SysWOW64\OneDriveSetup.exe } else { # Downloading the latest OneDrive try { if ((Invoke-WebRequest -Uri https://www.google.com -UseBasicParsing -DisableKeepAlive -Method Head).StatusDescription) { Write-Verbose -Message $Localization.OneDriveDownloading -Verbose [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $DownloadsFolder = Get-ItemPropertyValue -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name "{374DE290-123F-4565-9164-39C4925E467B}" $Parameters = @{ Uri = "https://go.microsoft.com/fwlink/p/?LinkID=2121808" OutFile = "$DownloadsFolder\OneDriveSetup.exe" Verbose = [switch]::Present } Invoke-WebRequest @Parameters Start-Process -FilePath "$DownloadsFolder\OneDriveSetup.exe" } } catch [System.Net.WebException] { Write-Warning -Message $Localization.NoInternetConnection } } Get-ScheduledTask -TaskName "Onedrive* Update*" | Start-ScheduledTask } } #endregion OneDrive #region System # Turn on Storage Sense (current user only) function EnableStorageSense { 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 } # Turn off Storage Sense (current user only) function DisableStorageSense { 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 } # Run Storage Sense every month (current user only) function StorageSenseMonthFrequency { 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 } } # Run Storage Sense during low free disk space (default value) (current user only) function StorageSenseDefaultFrequency { 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 } } # Delete temporary files that apps aren't using (current user only) function EnableStorageSenseTempFiles { 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 } } # Do not delete temporary files that apps aren't using (current user only) function DisableStorageSenseTempFiles { 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 } } # Delete files in recycle bin if they have been there for over 30 days (current user only) function EnableStorageSenseRecycleBin { 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 } } # Do not delete files in recycle bin if they have been there for over 30 days (current user only) function DisableStorageSenseRecycleBin { 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 } } # Disable hibernation if the device is not a laptop function DisableHibernate { if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2) { POWERCFG /HIBERNATE OFF } } # Turn on hibernate function EnableHibernate { POWERCFG /HIBERNATE ON } # Change the %TEMP% environment variable path to the %SystemDrive%\Temp (both machine-wide, and for the current user) function SetTempPath { 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) 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 Get-Item -Path $env:LOCALAPPDATA\Temp | Where-Object -FilterScript {$_.LinkType -ne "SymbolicLink"} | Remove-Item -Recurse -Force -ErrorAction Ignore # Create a symbolic link to the %SystemDrive%\Temp folder try { New-Item -Path $env:LOCALAPPDATA\Temp -ItemType SymbolicLink -Value $env:SystemDrive\Temp -Force } catch [System.Exception] { $Message = Invoke-Command -ScriptBlock ([ScriptBlock]::Create($Localization.LOCALAPPDATANotEmptyFolder)) Write-Error -Message $Message -ErrorAction SilentlyContinue } finally { Invoke-Item -Path $env:LOCALAPPDATA\Temp } } # Change the %TEMP% environment variable path to the %LOCALAPPDATA%\Temp (default value) (both machine-wide, and for the current user) function SetDefaultTempPath { # Remove a symbolic link to the %SystemDrive%\Temp folder (Get-Item -Path $env:LOCALAPPDATA\Temp -Force).Delete() if (-not (Test-Path -Path $env:SystemRoot\Temp)) { New-Item -Path $env:SystemRoot\Temp } if (-not (Test-Path -Path $env:LOCALAPPDATA\Temp)) { New-Item -Path $env:LOCALAPPDATA\Temp -ItemType Directory -Force } [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 %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 %LOCALAPPDATA%\Temp -Force New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name TMP -PropertyType ExpandString -Value %SystemRoot%\TEMP -Force New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name TEMP -PropertyType ExpandString -Value %SystemRoot%\TEMP -Force # Restart the Printer Spooler service (Spooler) Restart-Service -Name Spooler -Force Stop-Process -Name OneDrive -Force -ErrorAction Ignore Stop-Process -Name FileCoAuth -Force -ErrorAction Ignore Remove-Item -Path $env:SystemDrive\Temp -Recurse -Force -ErrorAction Ignore } # Enable Windows 260 character path limit function EnableWin32LongPaths { New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled -PropertyType DWord -Value 1 -Force } # Disable Windows 260 character path limit function DisableWin32LongPaths { New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled -PropertyType DWord -Value 0 -Force } # Display the Stop error information on the BSoD function EnableBSoDStopError { New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\CrashControl -Name DisplayParameters -PropertyType DWord -Value 1 -Force } # Do not display the Stop error information on the BSoD function DisableBSoDStopError { New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\CrashControl -Name DisplayParameters -PropertyType DWord -Value 0 -Force } # Change "Behavior of the elevation prompt for administrators in Admin Approval Mode" to "Elevate without prompting" function DisableAdminApprovalMode { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -PropertyType DWord -Value 0 -Force } # Change "Behavior of the elevation prompt for administrators in Admin Approval Mode" to "Prompt for consent for non-Windows binaries" (default value) function EnableAdminApprovalMode { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -PropertyType DWord -Value 5 -Force } # Turn on access to mapped drives from app running with elevated permissions with Admin Approval Mode enabled function EnableMappedDrivesAppElevatedAccess { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLinkedConnections -PropertyType DWord -Value 1 -Force } # Turn off access to mapped drives from app running with elevated permissions with Admin Approval Mode enabled function DisableMappedDrivesAppElevatedAccess { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLinkedConnections -PropertyType DWord -Value 0 -Force } # Opt out of the Delivery Optimization-assisted updates downloading function DisableDeliveryOptimization { New-ItemProperty -Path Registry::HKEY_USERS\S-1-5-20\SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Settings -Name DownloadMode -PropertyType DWord -Value 0 -Force Delete-DeliveryOptimizationCache -Force } # Opt-in to the Delivery Optimization-assisted updates downloading function EnableDeliveryOptimization { New-ItemProperty -Path Registry::HKEY_USERS\S-1-5-20\SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Settings -Name DownloadMode -PropertyType DWord -Value 1 -Force } # Always wait for the network at computer startup and logon for workgroup networks function AlwaysWaitNetworkStartup { 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 } } # Never wait for the network at computer startup and logon for workgroup networks function NeverWaitNetworkStartup { 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 } } # Do not let Windows decide which printer should be the default one (current user only) function DisableWindowsManageDefaultPrinter { New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name LegacyDefaultPrinterMode -PropertyType DWord -Value 1 -Force } # Let Windows decide which printer should be the default one (current user only) function EnableWindowsManageDefaultPrinter { New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name LegacyDefaultPrinterMode -PropertyType DWord -Value 0 -Force } # Disable the following Windows features function DisableWindowsFeatures { $WindowsOptionalFeatures = @( # Legacy Components "LegacyComponents", # Media Features "MediaPlayback", # PowerShell 2.0 "MicrosoftWindowsPowerShellV2", "MicrosoftWindowsPowershellV2Root", # Microsoft XPS Document Writer "Printing-XPSServices-Features", # Work Folders Client "WorkFolders-Client" ) Disable-WindowsOptionalFeature -Online -FeatureName $WindowsOptionalFeatures -NoRestart } # Enable the following Windows features function EnableWindowsFeatures { $WindowsOptionalFeatures = @( # Legacy Components "LegacyComponents", # Media Features "MediaPlayback", # PowerShell 2.0 "MicrosoftWindowsPowerShellV2", "MicrosoftWindowsPowershellV2Root", # Microsoft XPS Document Writer "Printing-XPSServices-Features", # Work Folders Client "WorkFolders-Client" ) Enable-WindowsOptionalFeature -Online -FeatureName $WindowsOptionalFeatures -NoRestart } <# Install the Windows Subsystem for Linux (WSL) https://github.com/farag2/Windows-10-Setup-Script/issues/43 https://github.com/microsoft/WSL/issues/5437 #> function InstallWSL { $WSLFeatures = @( # Windows Subsystem for Linux "Microsoft-Windows-Subsystem-Linux", # Virtual Machine Platform "VirtualMachinePlatform" ) Enable-WindowsOptionalFeature -Online -FeatureName $WSLFeatures -NoRestart } <# Download and install the Linux kernel update package Set WSL 2 as the default version when installing a new Linux distribution Run the function only after WSL installed and PC restart https://github.com/microsoft/WSL/issues/5437 #> function SetupWSL { if ((Get-Package -Name "Windows Subsystem for Linux Update" -ProviderName msi -Force -ErrorAction Ignore).Status -ne "Installed") { try { if ((Invoke-WebRequest -Uri https://www.google.com -UseBasicParsing -DisableKeepAlive -Method Head).StatusDescription) { Write-Verbose $Localization.WSLUpdateDownloading -Verbose [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $DownloadsFolder = Get-ItemPropertyValue -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name "{374DE290-123F-4565-9164-39C4925E467B}" $Parameters = @{ Uri = "https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi" OutFile = "$DownloadsFolder\wsl_update_x64.msi" Verbose = [switch]::Present } Invoke-WebRequest @Parameters Write-Verbose $Localization.WSLUpdateInstalling -Verbose Start-Process -FilePath "$DownloadsFolder\wsl_update_x64.msi" -ArgumentList "/passive" -Wait Remove-Item -Path "$DownloadsFolder\wsl_update_x64.msi" -Force } } catch [System.Net.WebException] { Write-Warning -Message $Localization.NoInternetConnection } } # Set WSL 2 as the default architecture when installing a new Linux distribution # To receive kernel updates, enable the Windows Update setting: 'Receive updates for other Microsoft products when you update Windows' if ((Get-Package -Name "Windows Subsystem for Linux Update" -ProviderName msi -Force -ErrorAction Ignore).Status -eq "Installed") { wsl --set-default-version 2 } } <# Disable swap file in WSL Use only if the %TEMP% environment variable path changed https://github.com/microsoft/WSL/issues/5437 #> function DisableWSLSwap { if ((Get-ItemPropertyValue -Path HKCU:\Environment -Name TEMP) -ne "$env:LOCALAPPDATA\Temp") { if (Test-Path -Path "$env:USERPROFILE\.wslconfig") { $String = Get-Content -Path "$env:USERPROFILE\.wslconfig" | Select-String -Pattern "swap=" -SimpleMatch if ($String) { (Get-Content -Path "$env:USERPROFILE\.wslconfig").Replace("swap=1", "swap=0") | Set-Content -Path "$env:USERPROFILE\.wslconfig" -Force } else { Add-Content -Path "$env:USERPROFILE\.wslconfig" -Value "`r`nswap=0" -Force } } else { $WSLConfig = @" [wsl2] swap=0 "@ # Saving .wslconfig in UTF-8 encoding Set-Content -Path "$env:USERPROFILE\.wslconfig" -Value $WSLConfig -Force } } } # Enable swap file in WSL # https://github.com/microsoft/WSL/issues/5437 function EnableWSLSwap { if (Test-Path -Path "$env:USERPROFILE\.wslconfig") { $String = Get-Content -Path "$env:USERPROFILE\.wslconfig" | Select-String -Pattern "swap=" -SimpleMatch if ($String) { (Get-Content -Path "$env:USERPROFILE\.wslconfig").Replace("swap=0", "swap=1") | Set-Content -Path "$env:USERPROFILE\.wslconfig" -Force } else { Add-Content -Path "$env:USERPROFILE\.wslconfig" -Value "`r`nswap=1" -Force } } else { $WSLConfig = @" [wsl2] swap=1 "@ # Saving .wslconfig in UTF-8 encoding Set-Content -Path "$env:USERPROFILE\.wslconfig" -Value $WSLConfig -Force } } # Uninstall the Windows Subsystem for Linux (WSL2) function UninstallWSL { $WSLFeatures = @( # Windows Subsystem for Linux "Microsoft-Windows-Subsystem-Linux", # Virtual Machine Platform "VirtualMachinePlatform" ) Disable-WindowsOptionalFeature -Online -FeatureName $WSLFeatures -NoRestart Uninstall-Package -Name "Windows Subsystem for Linux Update" -Force Remove-Item -Path "$env:USERPROFILE\.wslconfig" -Force -ErrorAction Ignore } # Disable certain Feature On Demand v2 (FODv2) capabilities function DisableWindowsCapabilities { 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 "Media.WindowsMediaPlayer*", # Microsoft Paint "Microsoft.Windows.MSPaint*", # WordPad "Microsoft.Windows.WordPad*", # Integrated faxing and scanning application for Windows "Print.Fax.Scan*" ) # If device is not a laptop disable "Hello.Face*" too if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2) { # Windows Hello Face $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\.Configuration\.Database", # Language components "Language\.", # Notepad "Microsoft.Windows.Notepad*", # Mail, contacts, and calendar sync component "OneCoreUAP\.OneSync", # Management of printers, printer drivers, and printer servers "Print\.Management\.Console", # Features critical to Windows functionality "Windows\.Client\.ShellComponents" ) #endregion Variables #region XAML Markup # The section defines the design of the upcoming dialog box [xml]$XAML = ' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="Window" MinHeight="450" MinWidth="400" SizeToContent="Width" WindowStartupLocation="CenterScreen" TextOptions.TextFormattingMode="Display" SnapsToDevicePixels="True" FontFamily="Segoe UI" FontSize="12" ShowInTaskbar="False"> <Window.Resources> <Style TargetType="StackPanel"> <Setter Property="Orientation" Value="Horizontal"/> </Style> <Style TargetType="CheckBox"> <Setter Property="Margin" Value="10, 10, 5, 10"/> <Setter Property="IsChecked" Value="True"/> </Style> <Style TargetType="TextBlock"> <Setter Property="Margin" Value="5, 10, 10, 10"/> </Style> <Style TargetType="Button"> <Setter Property="Margin" Value="20"/> <Setter Property="Padding" Value="10"/> </Style> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ScrollViewer Name="Scroll" Grid.Row="0" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto"> <StackPanel Name="PanelContainer" Orientation="Vertical"/> </ScrollViewer> <Button Name="Button" Grid.Row="1"/> </Grid> </Window> ' #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.Add_Loaded({ $OFS = "|" (Get-WindowsCapability -Online | Where-Object -FilterScript {($_.State -eq "Installed") -and ($_.Name -cnotmatch $ExcludedCapabilities)}).Name | ForEach-Object -Process { Add-CapabilityControl -Capability $_ } $OFS = " " $Window.Title = $Localization.FODWindowTitle $Button.Content = $Localization.FODWindowButton }) # 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 "|"))}) { Write-Verbose -Message $Localization.DialogBoxOpening -Verbose # Display the dialog box $Form.ShowDialog() | Out-Null } else { Write-Verbose -Message $Localization.NoData -Verbose } } # Opt-in to Microsoft Update service, so to receive updates for other Microsoft products function EnableUpdatesMicrosoftProducts { (New-Object -ComObject Microsoft.Update.ServiceManager).AddService2("7971f918-a847-4430-9279-4a52d1efe18d", 7, "") } # Opt-out of Microsoft Update service, so not to receive updates for other Microsoft products function DisableUpdatesMicrosoftProducts { 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") } } # Do not let UWP apps run in the background, except the followings... (current user only) function DisableBackgroundUWPApps { Get-ChildItem -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications | ForEach-Object -Process { Remove-ItemProperty -Path $_.PsPath -Name * -Force } $ExcludedBackgroundApps = @( # Lock screen app "Microsoft.LockApp", # Content Delivery Manager (delivers Windows Spotlight wallpapers to the lock screen) "Microsoft.Windows.ContentDeliveryManager", # Cortana "Microsoft.Windows.Cortana", # Windows Search "Microsoft.Windows.Search", # Windows Security "Microsoft.Windows.SecHealthUI", # Windows Shell Experience (Action center, snipping support, toast notification, touch screen keyboard) "Microsoft.Windows.ShellExperienceHost", # The Start menu "Microsoft.Windows.StartMenuExperienceHost", # Microsoft Store "Microsoft.WindowsStore" ) $OFS = "|" Get-ChildItem -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications | Where-Object -FilterScript {$_.PSChildName -notmatch "^$($ExcludedBackgroundApps.ForEach({[regex]::Escape($_)}))"} | ForEach-Object -Process { New-ItemProperty -Path $_.PsPath -Name Disabled -PropertyType DWord -Value 1 -Force New-ItemProperty -Path $_.PsPath -Name DisabledByUser -PropertyType DWord -Value 1 -Force } $OFS = " " # Open "Background apps" page Start-Process -FilePath ms-settings:privacy-backgroundapps } # Let UWP apps run in the background (current user only) function EnableBackgroundUWPApps { Get-ChildItem -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications | ForEach-Object -Process { Remove-ItemProperty -Path $_.PsPath -Name * -Force } } # Set the power management scheme on "High performance" if device is a desktop function DesktopPowerManagementScheme { if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -eq 1) { POWERCFG /SETACTIVE SCHEME_MIN } } # Set the power management scheme on "Balanced" (default value) function DefaultPowerManagementScheme { POWERCFG /SETACTIVE SCHEME_BALANCED } # Use latest installed .NET runtime for all apps function EnableLatestInstalled.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 } # Do not use latest installed .NET runtime for all apps function DisableLatestInstalled.NET { 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 } # Do not allow the computer (if device is not a laptop) to turn off the network adapters to save power function DisallowPCTurnOffDevice { 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 } } } # Allow the computer to turn off the network adapters to save power function AllowPCTurnOffDevice { 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 = "Enabled" $Adapter | Set-NetAdapterPowerManagement } } } # Set the default input method to the English language function SetEnglishDefaultInputMethod { Set-WinDefaultInputMethodOverride -InputTip "0409:00000409" } # Reset the default input method function ResetDefaultInputMethod { Remove-ItemProperty -Path "HKCU:\Control Panel\International\User Profile" -Name InputMethodOverride -Force -ErrorAction SilentlyContinue } # Enable Windows Sandbox function EnableWindowsSandbox { if (Get-WindowsEdition -Online | Where-Object -FilterScript {$_.Edition -eq "Professional" -or $_.Edition -like "Enterprise*"}) { # Checking whether x86 virtualization is enabled in the firmware 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 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 } } } } # Disable Windows Sandbox function DisableWindowsSandbox { if (Get-WindowsEdition -Online | Where-Object -FilterScript {$_.Edition -eq "Professional" -or $_.Edition -like "Enterprise*"}) { # Checking whether x86 virtualization is enabled in the firmware if ((Get-CimInstance -ClassName CIM_Processor).VirtualizationFirmwareEnabled -eq $true) { Disable-WindowsOptionalFeature -FeatureName Containers-DisposableClientVM -Online -NoRestart } else { try { # Determining whether Hyper-V is enabled 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 } } } } <# Change the location of the user folders to any drives root (current user only) It is suggested to move it to any disks root of your choice using the interactive menu by default User files or folders won't me moved to a new location #> function ChangeUserShellFolderLocation { function UserShellFolder { <# .SYNOPSIS Change the location of the each user folders using SHSetKnownFolderPath function https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath .EXAMPLE UserShellFolder -UserFolder Desktop -FolderPath "$env:SystemDrive:\Desktop" -RemoveDesktopINI .NOTES User files or folders won't me moved to a new location The RemoveDesktopINI argument removes desktop.ini in the old user shell folder #> [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 $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) { $Message = Invoke-Command -ScriptBlock ([ScriptBlock]::Create($Localization.UserShellFolderNotEmpty)) Write-Error -Message $Message -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 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 .EXAMPLE ShowMenu -Menu $ListOfItems -Default $DefaultChoice .NOTES 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)) } # Store all drives letters to use them within ShowMenu function Write-Verbose $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) { $Default = 1 } else { $Default = 0 } # Desktop Write-Verbose -Message $Localization.DesktopDriveSelect -Verbose Write-Warning -Message $Localization.DesktopFilesWontBeMoved $Title = "" $Message = $Localization.DesktopFolderRequest $Change = $Localization.DesktopFolderChange $Skip = $Localization.DesktopFolderSkip $Options = "&$Change", "&$Skip" $DefaultChoice = 1 $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) switch ($Result) { "0" { $SelectedDrive = ShowMenu -Title $Localization.DesktopDriveSelect -Menu $DriveLetters -Default $Default UserShellFolder -UserFolder Desktop -FolderPath "${SelectedDrive}:\Desktop" -RemoveDesktopINI } "1" { Write-Verbose -Message $Localization.DesktopSkipped -Verbose } } # Documents Write-Verbose -Message $Localization.DocumentsDriveSelect -Verbose Write-Warning -Message $Localization.DocumentsFilesWontBeMoved $Title = "" $Message = $Localization.DocumentsFolderRequest $Change = $Localization.DocumentsFolderChange $Skip = $Localization.DocumentsFolderSkip $Options = "&$Change", "&$Skip" $DefaultChoice = 1 $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) switch ($Result) { "0" { $SelectedDrive = ShowMenu -Title $Localization.DocumentsDriveSelect -Menu $DriveLetters -Default $Default UserShellFolder -UserFolder Documents -FolderPath "${SelectedDrive}:\Documents" -RemoveDesktopINI } "1" { Write-Verbose -Message $Localization.DocumentsSkipped -Verbose } } # Downloads Write-Verbose -Message $Localization.DownloadsDriveSelect -Verbose Write-Warning -Message $Localization.DownloadsFilesWontBeMoved $Title = "" $Message = $Localization.DownloadsFolderRequest $Change = $Localization.DownloadsFolderChange $Skip = $Localization.DownloadsFolderSkip $Options = "&$Change", "&$Skip" $DefaultChoice = 1 $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) switch ($Result) { "0" { $SelectedDrive = ShowMenu -Title $Localization.DownloadsDriveSelect -Menu $DriveLetters -Default $Default UserShellFolder -UserFolder Downloads -FolderPath "${SelectedDrive}:\Downloads" -RemoveDesktopINI } "1" { Write-Verbose -Message $Localization.DownloadsSkipped -Verbose } } # Music Write-Verbose -Message $Localization.MusicDriveSelect -Verbose Write-Warning -Message $Localization.MusicFilesWontBeMoved $Title = "" $Message = $Localization.MusicFolderRequest $Change = $Localization.MusicFolderChange $Skip = $Localization.MusicFolderSkip $Options = "&$Change", "&$Skip" $DefaultChoice = 1 $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) switch ($Result) { "0" { $SelectedDrive = ShowMenu -Title $Localization.MusicDriveSelect -Menu $DriveLetters -Default $Default UserShellFolder -UserFolder Music -FolderPath "${SelectedDrive}:\Music" -RemoveDesktopINI } "1" { Write-Verbose -Message $Localization.MusicSkipped -Verbose } } # Pictures Write-Verbose -Message $Localization.PicturesDriveSelect -Verbose Write-Warning -Message $Localization.PicturesFilesWontBeMoved $Title = "" $Message = $Localization.PicturesFolderRequest $Change = $Localization.PicturesFolderChange $Skip = $Localization.PicturesFolderSkip $Options = "&$Change", "&$Skip" $DefaultChoice = 1 $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) switch ($Result) { "0" { $SelectedDrive = ShowMenu -Title $Localization.PicturesDriveSelect -Menu $DriveLetters -Default $Default UserShellFolder -UserFolder Pictures -FolderPath "${SelectedDrive}:\Pictures" -RemoveDesktopINI } "1" { Write-Verbose -Message $Localization.PicturesSkipped -Verbose } } # Videos Write-Verbose -Message $Localization.VideosDriveSelect -Verbose Write-Warning -Message $Localization.VideosFilesWontBeMoved $Title = "" $Message = $Localization.VideosFolderRequest $Change = $Localization.VideosFolderChange $Skip = $Localization.VideosFolderSkip $Options = "&$Change", "&$Skip" $DefaultChoice = 1 $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice) switch ($Result) { "0" { $SelectedDrive = ShowMenu -Title $Localization.VideosDriveSelect -Menu $DriveLetters -Default $Default UserShellFolder -UserFolder Videos -FolderPath "${SelectedDrive}:\Videos" -RemoveDesktopINI } "1" { Write-Verbose -Message $Localization.VideosSkipped -Verbose } } } # 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 function SetDefaultUserShellFolderLocation { function UserShellFolder { <# .SYNOPSIS Change the location of the each user folders using SHSetKnownFolderPath function https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath .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 #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateSet("Desktop", "Documents", "Downloads", "Music", "Pictures", "Videos")] [string] $UserFolder, [Parameter(Mandatory = $true)] [string] $FolderPath, [switch] $RemoveDesktopINI ) function KnownFolderPath { <# .SYNOPSIS Redirect user folders to a new location .EXAMPLE KnownFolderPath -KnownFolder Desktop -Path "C:\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 $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 -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 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() } } # Desktop Write-Verbose -Message $Localization.DesktopDriveSelect -Verbose Write-Warning -Message $Localization.DesktopFilesWontBeMoved $Title = "" $Message = $Localization.DesktopDefaultFolder $Change = $Localization.DesktopFolderChange $Skip = $Localization.DesktopFolderSkip $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.DesktopSkipped -Verbose } } # Documents Write-Verbose -Message $Localization.DocumentsDriveSelect -Verbose Write-Warning -Message $Localization.DocumentsFilesWontBeMoved $Title = "" $Message = $Localization.DocumentsDefaultFolder $Change = $Localization.DocumentsFolderChange $Skip = $Localization.DocumentsFolderSkip $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.DocumentsSkipped -Verbose } } # Downloads Write-Verbose -Message $Localization.DownloadsDriveSelect -Verbose Write-Warning -Message $Localization.DownloadsFilesWontBeMoved $Title = "" $Message = $Localization.DownloadsDefaultFolder $Change = $Localization.DownloadsFolderChange $Skip = $Localization.DownloadsFolderSkip $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.DownloadsSkipped -Verbose } } # Music Write-Verbose -Message $Localization.MusicDriveSelect -Verbose Write-Warning -Message $Localization.MusicFilesWontBeMoved $Title = "" $Message = $Localization.MusicDefaultFolder $Change = $Localization.MusicFolderChange $Skip = $Localization.MusicFolderSkip $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.MusicSkipped -Verbose } } # Pictures Write-Verbose -Message $Localization.PicturesDriveSelect -Verbose Write-Warning -Message $Localization.PicturesFilesWontBeMoved $Title = "" $Message = $Localization.PicturesDefaultFolder $Change = $Localization.PicturesFolderChange $Skip = $Localization.PicturesFolderSkip $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.PicturesSkipped -Verbose } } # Videos Write-Verbose -Message $Localization.VideosDriveSelect -Verbose Write-Warning -Message $Localization.VideosFilesWontBeMoved $Title = "" $Message = $Localization.VideosDefaultFolder $Change = $Localization.VideosFolderChange $Skip = $Localization.VideosFolderSkip $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.VideosSkipped -Verbose } } } # Save screenshots by pressing Win+PrtScr to the Desktop folder (current user only) function WinPrtScrDesktopFolder { $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 # Restoring closed folders foreach ($OpenedFolder in $OpenedFolders) { if (Test-Path -Path $OpenedFolder) { Invoke-Item -Path $OpenedFolder } } } # Save screenshots by pressing Win+PrtScr to the Pictures folder (default value) (current user only) function WinPrtScrDefaultFolder { 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 } } } # Run troubleshooters automatically, then notify # In order this feature to work the OS level of diagnostic data gathering must be set to "Full" function AutomaticRecommendedTroubleshooting { if (-not (Test-Path -Path HKLM:\SOFTWARE\Microsoft\WindowsMitigation)) { New-Item -Path HKLM:\SOFTWARE\Microsoft\WindowsMitigation -Force } New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsMitigation -Name UserPreference -PropertyType DWord -Value 3 -Force # Set the OS level of diagnostic data gathering to "Full" New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 3 -Force } # Ask me before running troubleshooters (default value) # In order this feature to work the OS level of diagnostic data gathering must be set to "Full" function DefaultRecommendedTroubleshooting { if (-not (Test-Path -Path HKLM:\SOFTWARE\Microsoft\WindowsMitigation)) { New-Item -Path HKLM:\SOFTWARE\Microsoft\WindowsMitigation -Force } New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsMitigation -Name UserPreference -PropertyType DWord -Value 2 -Force # Set the OS level of diagnostic data gathering to "Full" New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 3 -Force } # Launch folder windows in a separate process (current user only) function EnableFoldersLaunchSeparateProcess { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SeparateProcess -PropertyType DWord -Value 1 -Force } # Do not folder windows in a separate process (current user only) function DisableFoldersLaunchSeparateProcess { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name SeparateProcess -PropertyType DWord -Value 0 -Force } # Disable and delete reserved storage after the next update installation function DisableReservedStorage { try { Set-WindowsReservedStorageState -State Disabled } catch [System.Runtime.InteropServices.COMException] { Write-Error -Message $Localization.ReservedStorageIsInUse -ErrorAction SilentlyContinue } } # Turn on reserved storage function EnableReservedStorage { Set-WindowsReservedStorageState -State Enabled } # Disable help lookup via F1 (current user only) function DisableF1HelpPage { 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 } # Turn on Help page opening by F1 key (current user only) function EnableF1HelpPage { Remove-Item -Path "HKCU:\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}" -Recurse -Force -ErrorAction SilentlyContinue } # Turn on Num Lock at startup function EnableNumLock { New-ItemProperty -Path "Registry::HKEY_USERS\.DEFAULT\Control Panel\Keyboard" -Name InitialKeyboardIndicators -PropertyType String -Value 2147483650 -Force } # Turn off Num Lock at startup function DisableNumLock { New-ItemProperty -Path "Registry::HKEY_USERS\.DEFAULT\Control Panel\Keyboard" -Name InitialKeyboardIndicators -PropertyType String -Value 2147483648 -Force } # Do not activate StickyKey after tapping the Shift key 5 times (current user only) function DisableStickyShift { New-ItemProperty -Path "HKCU:\Control Panel\Accessibility\StickyKeys" -Name Flags -PropertyType String -Value 506 -Force } # Activate StickyKey after tapping the Shift key 5 times (current user only) function EnableStickyShift { New-ItemProperty -Path "HKCU:\Control Panel\Accessibility\StickyKeys" -Name Flags -PropertyType String -Value 510 -Force } # Do not use AutoPlay for all media and devices (current user only) function DisableAutoplay { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -PropertyType DWord -Value 1 -Force } # Use AutoPlay for all media and devices (current user only) function EnableAutoplay { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -PropertyType DWord -Value 0 -Force } # Disable thumbnail cache removal function DisableThumbnailCacheRemoval { New-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Thumbnail Cache" -Name Autorun -PropertyType DWord -Value 0 -Force } # Enable thumbnail cache removal function EnableThumbnailCacheRemoval { New-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Thumbnail Cache" -Name Autorun -PropertyType DWord -Value 3 -Force } # Automatically save my restartable apps when signing out and restart them after signing in (current user only) function EnableSaveRestartableApps { New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name RestartApps -Value 1 -Force } # Do not automatically save my restartable apps when signing out and restart them after signing in function DisableSaveRestartableApps { New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name RestartApps -Value 0 -Force } # Enable "Network Discovery" and "File and Printers Sharing" for workgroup networks function EnableNetworkDiscovery { 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 Set-NetFirewallRule -Profile Public, Private -Name FPS-SMB-In-TCP -Enabled True Set-NetConnectionProfile -NetworkCategory Private } } # Disable "Network Discovery" and "File and Printers Sharing" for workgroup networks function DisableNetworkDiscovery { 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 False } } # Automatically adjust active hours for me based on daily usage function EnableSmartActiveHours { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name SmartActiveHoursState -PropertyType DWord -Value 1 -Force } # Do not automatically adjust active hours for me based on daily usage function DisableSmartActiveHours { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name SmartActiveHoursState -PropertyType DWord -Value 2 -Force } # Restart this device as soon as possible when a restart is required to install an update function EnableDeviceRestartAfterUpdate { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name IsExpedited -PropertyType DWord -Value 1 -Force } # Do not restart this device as soon as possible when a restart is required to install an update function DisableDeviceRestartAfterUpdate { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings -Name IsExpedited -PropertyType DWord -Value 0 -Force } #endregion System #region Start menu # Do not show recently added apps in the Start menu function HideRecentlyAddedApps { 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 recently added apps in the Start menu function ShowRecentlyAddedApps { Remove-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name HideRecentlyAddedApps -Force -ErrorAction SilentlyContinue } # Do not show app suggestions in the Start menu function HideAppSuggestions { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338388Enabled -PropertyType DWord -Value 0 -Force } # Show app suggestions in the Start menu function ShowAppSuggestions { New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager -Name SubscribedContent-338388Enabled -PropertyType DWord -Value 1 -Force } # Run the Command Prompt shortcut from the Start menu as Administrator function RunCMDShortcutElevated { [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 } # Run the Command Prompt shortcut from the Start menu as user function RunCMDShortcutUser { [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 } # Unpin all the Start tiles function UnpinAllStartTiles { $StartMenuLayout = @" <LayoutModificationTemplate xmlns:defaultlayout="http://schemas.microsoft.com/Start/2014/FullDefaultLayout" xmlns:start="http://schemas.microsoft.com/Start/2014/StartLayout" Version="1" xmlns="http://schemas.microsoft.com/Start/2014/LayoutModification"> <LayoutOptions StartTileGroupCellWidth="6" /> <DefaultLayoutOverride> <StartLayoutCollection> <defaultlayout:StartLayout GroupCellWidth="6" /> </StartLayoutCollection> </DefaultLayoutOverride> </LayoutModificationTemplate> "@ $StartMenuLayoutPath = "$env:TEMP\StartMenuLayout.xml" # Saving StartMenuLayout.xml in UTF-8 encoding Set-Content -Path $StartMenuLayoutPath -Value (New-Object -TypeName System.Text.UTF8Encoding).GetBytes($StartMenuLayout) -Encoding Byte -Force # Temporarily disable changing the Start menu layout if (-not (Test-Path -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer)) { New-Item -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Force } New-ItemProperty -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name LockedStartLayout -Value 1 -Force New-ItemProperty -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name StartLayoutFile -Value $StartMenuLayoutPath -Force # Restart the Start menu Stop-Process -Name StartMenuExperienceHost -Force -ErrorAction Ignore Start-Sleep -Seconds 3 Remove-ItemProperty -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name LockedStartLayout -Force -ErrorAction Ignore Remove-ItemProperty -Path HKCU:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name StartLayoutFile -Force -ErrorAction Ignore Stop-Process -Name StartMenuExperienceHost -Force -ErrorAction Ignore Get-Item -Path $StartMenuLayoutPath | Remove-Item -Force -ErrorAction Ignore } <# Pin the "Control Panel" shortcut to Start within syspin http://www.technosys.net/products/utils/pintotaskbar SHA256: 6967E7A3C2251812DD6B3FA0265FB7B61AADC568F562A98C50C345908C6E827 #> function PinControlPanel { if (Test-Path -Path $PSScriptRoot\syspin.exe) { $syspin = $true } else { try { # Downloading syspin if ((Invoke-WebRequest -Uri https://www.google.com -UseBasicParsing -DisableKeepAlive -Method Head).StatusDescription) { Write-Verbose -Message $Localization.syspinDownloading -Verbose [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $DownloadsFolder = Get-ItemPropertyValue -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name "{374DE290-123F-4565-9164-39C4925E467B}" $Parameters = @{ Uri = "https://github.com/farag2/Windows-10-Setup-Script/raw/master/Start%20menu%20pinning/syspin.exe" OutFile = "$DownloadsFolder\syspin.exe" Verbose = [switch]::Present } Invoke-WebRequest @Parameters Move-Item -Path "$DownloadsFolder\syspin.exe" -Destination $PSScriptRoot -Force $syspin = $true } } catch [System.Net.WebException] { Write-Warning -Message $Localization.NoInternetConnection } } if ($syspin -eq $true) { $Items = (New-Object -ComObject Shell.Application).NameSpace("shell:::{4234d49b-0245-4df3-b780-3893943456e1}").Items() $ControlPanelLocalizedName = ($Items | Where-Object -FilterScript {$_.Path -eq "Microsoft.Windows.ControlPanel"}).Name $Message = Invoke-Command -ScriptBlock ([ScriptBlock]::Create($Localization.ControlPanelPinning)) Write-Verbose -Message $Message -Verbose # Check whether the Control Panel shortcut was ever pinned if (Test-Path -Path "$env:APPDATA\Microsoft\Windows\Start menu\Programs\$ControlPanelLocalizedName.lnk") { $Arguments = @" "$env:APPDATA\Microsoft\Windows\Start menu\Programs\$ControlPanelLocalizedName.lnk" "51201" "@ Start-Process -FilePath $PSScriptRoot\syspin.exe -WindowStyle Hidden -ArgumentList $Arguments -Wait } else { # The "Pin" verb is not available on the control.exe file so the shortcut has to be created $Shell = New-Object -ComObject Wscript.Shell $Shortcut = $Shell.CreateShortcut("$env:SystemRoot\System32\$ControlPanelLocalizedName.lnk") $Shortcut.TargetPath = "$env:SystemRoot\System32\control.exe" $Shortcut.Save() $Arguments = @" "$env:SystemRoot\System32\$ControlPanelLocalizedName.lnk" "51201" "@ Start-Process -FilePath $PSScriptRoot\syspin.exe -WindowStyle Hidden -ArgumentList $Arguments -Wait Remove-Item -Path "$env:SystemRoot\System32\$ControlPanelLocalizedName.lnk" -Force -ErrorAction Ignore } # Restart the Start menu Stop-Process -Name StartMenuExperienceHost -Force -ErrorAction Ignore } } <# Pin the old-style "Devices and Printers" shortcut to Start within syspin http://www.technosys.net/products/utils/pintotaskbar SHA256: 6967E7A3C2251812DD6B3FA0265FB7B61AADC568F562A98C50C345908C6E827 #> function PinDevicesPrinters { if (Test-Path -Path $PSScriptRoot\syspin.exe) { $syspin = $true } else { try { # Downloading syspin if ((Invoke-WebRequest -Uri https://www.google.com -UseBasicParsing -DisableKeepAlive -Method Head).StatusDescription) { Write-Verbose -Message $Localization.syspinDownloading -Verbose [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $DownloadsFolder = Get-ItemPropertyValue -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name "{374DE290-123F-4565-9164-39C4925E467B}" $Parameters = @{ Uri = "https://github.com/farag2/Windows-10-Setup-Script/raw/master/Start%20menu%20pinning/syspin.exe" OutFile = "$DownloadsFolder\syspin.exe" Verbose = [switch]::Present } Invoke-WebRequest @Parameters Move-Item -Path "$DownloadsFolder\syspin.exe" -Destination $PSScriptRoot -Force $syspin = $true } } catch [System.Net.WebException] { Write-Warning -Message $Localization.NoInternetConnection } } if ($syspin -eq $true) { $DevicesAndPrintersLocalizedName = (Get-ControlPanelItem -CanonicalName "Microsoft.DevicesAndPrinters").Name $Message = Invoke-Command -ScriptBlock ([ScriptBlock]::Create($Localization.DevicesPrintersPinning)) Write-Verbose -Message $Message -Verbose $Shell = New-Object -ComObject Wscript.Shell $Shortcut = $Shell.CreateShortcut("$env:APPDATA\Microsoft\Windows\Start menu\Programs\System Tools\$DevicesAndPrintersLocalizedName.lnk") $Shortcut.TargetPath = "control" $Shortcut.Arguments = "printers" $Shortcut.IconLocation = "$env:SystemRoot\system32\DeviceCenter.dll" $Shortcut.Save() # Pause for 3 sec, unless the "Devices and Printers" shortcut won't displayed in the Start menu Start-Sleep -Seconds 3 $Arguments = @" "$env:APPDATA\Microsoft\Windows\Start menu\Programs\System Tools\$DevicesAndPrintersLocalizedName.lnk" "51201" "@ Start-Process -FilePath $PSScriptRoot\syspin.exe -WindowStyle Hidden -ArgumentList $Arguments -Wait } } <# Pin the "Command Prompt" shortcut to Start within syspin http://www.technosys.net/products/utils/pintotaskbar SHA256: 6967E7A3C2251812DD6B3FA0265FB7B61AADC568F562A98C50C345908C6E827 #> function PinCommandPrompt { if (Test-Path -Path $PSScriptRoot\syspin.exe) { $syspin = $true } else { try { # Downloading syspin if ((Invoke-WebRequest -Uri https://www.google.com -UseBasicParsing -DisableKeepAlive -Method Head).StatusDescription) { Write-Verbose -Message $Localization.syspinDownloading -Verbose [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $DownloadsFolder = Get-ItemPropertyValue -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name "{374DE290-123F-4565-9164-39C4925E467B}" $Parameters = @{ Uri = "https://github.com/farag2/Windows-10-Setup-Script/raw/master/Start%20menu%20pinning/syspin.exe" OutFile = "$DownloadsFolder\syspin.exe" Verbose = [switch]::Present } Invoke-WebRequest @Parameters Move-Item -Path "$DownloadsFolder\syspin.exe" -Destination $PSScriptRoot -Force $syspin = $true } } catch [System.Net.WebException] { Write-Warning -Message $Localization.NoInternetConnection } } if ($syspin -eq $true) { Write-Verbose -Message $Localization.CMDPinning -Verbose $Arguments = @" "$env:APPDATA\Microsoft\Windows\Start menu\Programs\System Tools\Command Prompt.lnk" "51201" "@ Start-Process -FilePath $PSScriptRoot\syspin.exe -WindowStyle Hidden -ArgumentList $Arguments -Wait # Restart the Start menu Stop-Process -Name StartMenuExperienceHost -Force -ErrorAction Ignore } } #endregion Start menu #region UWP apps <# Uninstall UWP apps A dialog box that enables the user to select packages to remove App packages will not be installed for new users if "Uninstall for All Users" is checked Add UWP apps packages names to the $UncheckedAppXPackages array list by retrieving their packages names using the following command: (Get-AppxPackage -PackageTypeFilter Bundle -AllUsers).Name #> function UninstallUWPApps { Add-Type -AssemblyName PresentationCore, PresentationFramework #region Variables # ArrayList containing the UWP apps to remove $AppxPackages = New-Object -TypeName System.Collections.ArrayList($null) # List of UWP apps that won't be recommended for removal $UncheckedAppxPackages = @( # AMD Radeon UWP panel "AdvancedMicroDevicesInc*", # Intel Graphics Control Center "AppUp.IntelGraphicsControlPanel", "AppUp.IntelGraphicsExperience", # Sticky Notes "Microsoft.MicrosoftStickyNotes", # Screen Sketch "Microsoft.ScreenSketch", # Photos (and Video Editor) "Microsoft.Windows.Photos", "Microsoft.Photos.MediaEngineDLC", # Calculator "Microsoft.WindowsCalculator", # Xbox Identity Provider "Microsoft.XboxIdentityProvider", # Xbox "Microsoft.XboxApp", # Xbox (beta version) "Microsoft.GamingApp", "Microsoft.GamingServices", # Xbox TCUI "Microsoft.Xbox.TCUI", # Xbox Speech To Text Overlay "Microsoft.XboxSpeechToTextOverlay", # Xbox Game Bar "Microsoft.XboxGamingOverlay", # Xbox Game Bar Plugin "Microsoft.XboxGameOverlay", # NVIDIA Control Panel "NVIDIACorp.NVIDIAControlPanel", # Realtek Audio Console "RealtekSemiconductorCorp.RealtekAudioControl" ) # UWP apps that won't be shown in the form $ExcludedAppxPackages = @( # Microsoft Desktop App Installer "Microsoft.DesktopAppInstaller", # Store Experience Host "Microsoft.StorePurchaseApp", # Microsoft Store "Microsoft.WindowsStore", # Web Media Extensions "Microsoft.WebMediaExtensions" ) #endregion Variables #region XAML Markup [xml]$XAML = ' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="Window" MinHeight="450" MinWidth="400" SizeToContent="Width" WindowStartupLocation="CenterScreen" TextOptions.TextFormattingMode="Display" SnapsToDevicePixels="True" FontFamily="Segoe UI" FontSize="12" ShowInTaskbar="False"> <Window.Resources> <Style TargetType="StackPanel"> <Setter Property="Orientation" Value="Horizontal"/> </Style> <Style TargetType="CheckBox"> <Setter Property="Margin" Value="10, 10, 5, 10"/> <Setter Property="IsChecked" Value="True"/> </Style> <Style TargetType="TextBlock"> <Setter Property="Margin" Value="5, 10, 10, 10"/> </Style> <Style TargetType="Button"> <Setter Property="Margin" Value="20"/> <Setter Property="Padding" Value="10"/> </Style> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid Grid.Row="0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <StackPanel Grid.Column="1" Orientation="Horizontal"> <CheckBox Name="CheckboxRemoveAll" IsChecked="False"/> <TextBlock Name="TextblockRemoveAll"/> </StackPanel> </Grid> <ScrollViewer Name="Scroll" Grid.Row="1" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto"> <StackPanel Name="PanelContainer" Orientation="Vertical"/> </ScrollViewer> <Button Name="Button" Grid.Row="2"/> </Grid> </Window> ' #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 ) $AppxName = $CheckBox.Parent.Children[1].Text if ($CheckBox.IsChecked) { [void]$AppxPackages.Add($AppxName) } else { [void]$AppxPackages.Remove($AppxName) } if ($AppxPackages.Count -gt 0) { $Button.IsEnabled = $true } else { $Button.IsEnabled = $false } } function DeleteButton { [void]$Window.Close() $OFS = "|" if ($CheckboxRemoveAll.IsChecked) { Get-AppxPackage -PackageTypeFilter Bundle -AllUsers | Where-Object -FilterScript {$_.Name -cmatch $AppxPackages} | Remove-AppxPackage -AllUsers -Verbose } else { Get-AppxPackage -PackageTypeFilter Bundle | Where-Object -FilterScript {$_.Name -cmatch $AppxPackages} | Remove-AppxPackage -Verbose } $OFS = " " } function Add-AppxControl { [CmdletBinding()] param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [ValidateNotNull()] [string] $AppxName ) $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 = $AppxName $StackPanel = New-Object -TypeName System.Windows.Controls.StackPanel [void]$StackPanel.Children.Add($CheckBox) [void]$StackPanel.Children.Add($TextBlock) [void]$PanelContainer.Children.Add($StackPanel) if ($UncheckedAppxPackages.Contains($AppxName)) { $CheckBox.IsChecked = $false # Exit function, item is not checked return } # If package checked, add to the array list to uninstall [void]$AppxPackages.Add($AppxName) } #endregion Functions #region Events Handlers $Window.Add_Loaded({ $OFS = "|" (Get-AppxPackage -PackageTypeFilter Bundle -AllUsers | Where-Object -FilterScript {$_.Name -cnotmatch $ExcludedAppxPackages}).Name | ForEach-Object -Process { Add-AppxControl -AppxName $_ } $OFS = " " $TextblockRemoveAll.Text = $Localization.UninstallUWPForAll $Window.Title = $Localization.UninstallUWPTitle $Button.Content = $Localization.UninstallUWPUninstallButton }) # Button Click Event $Button.Add_Click({DeleteButton}) #endregion Events Handlers if (Get-AppxPackage -PackageTypeFilter Bundle -AllUsers | Where-Object -FilterScript {$_.Name -cnotmatch ($ExcludedAppxPackages -join "|")}) { Write-Verbose -Message $Localization.DialogBoxOpening -Verbose # Display the dialog box $Form.ShowDialog() | Out-Null } else { Write-Verbose -Message $Localization.NoData -Verbose } } <# Open Microsoft Store "HEVC Video Extensions from Device Manufacturer" page The extension can be installed without Microsoft account for free instead of $0.99 "Movies & TV" app required #> function InstallHEVC { if (Get-AppxPackage -Name Microsoft.ZuneVideo) { Start-Process -FilePath ms-windows-store://pdp/?ProductId=9n4wgh0z6vhq } } # Turn off Cortana autostarting function DisableCortanaAutostart { if (Get-AppxPackage -Name Microsoft.549981C3F5F10) { if (-not (Test-Path -Path "Registry::HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\SystemAppData\Microsoft.549981C3F5F10_8wekyb3d8bbwe\CortanaStartupId")) { New-Item -Path "Registry::HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\SystemAppData\Microsoft.549981C3F5F10_8wekyb3d8bbwe\CortanaStartupId" -Force } New-ItemProperty -Path "Registry::HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\SystemAppData\Microsoft.549981C3F5F10_8wekyb3d8bbwe\CortanaStartupId" -Name State -PropertyType DWord -Value 1 -Force } } # Turn on Cortana autostarting function EnableCortanaAutostart { if (Get-AppxPackage -Name Microsoft.549981C3F5F10) { Remove-ItemProperty -Path "Registry::HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\SystemAppData\Microsoft.549981C3F5F10_8wekyb3d8bbwe\CortanaStartupId" -Name State -Force -ErrorAction SilentlyContinue } } # Check for UWP apps updates function CheckUWPAppsUpdates { Get-CimInstance -Namespace "Root\cimv2\mdm\dmmap" -ClassName "MDM_EnterpriseModernAppManagement_AppManagement01" | Invoke-CimMethod -MethodName UpdateScanMethod } #endregion UWP apps #region Gaming # Turn off Xbox Game Bar function DisableXboxGameBar { 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 } } # Turn on Xbox Game Bar function EnableXboxGameBar { 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 } } # Turn off Xbox Game Bar tips function DisableXboxGameTips { 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 } } # Turn on Xbox Game Bar tips function EnableXboxGameTips { 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.GraphicsPerformanceAdd $Skip = $Localization.GraphicsPerformanceSkip $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.GraphicsPerformanceFilter $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 Write-Verbose -Message ("{0}" -f $OpenFileDialog.FileName) -Verbose } } "1" { Write-Verbose -Message $Localization.GraphicsPerformanceSkipped -Verbose } } } until ($Result -eq 1) } } # Turn on hardware-accelerated GPU scheduling. Restart needed # Only with a dedicated GPU and WDDM verion is 2.7 or higher function EnableGPUScheduling { if ((Get-CimInstance -ClassName CIM_VideoController | Where-Object -FilterScript {$_.AdapterDACType -ne "Internal"})) { # Determining whether an OS is not installed on a virtual machine if ((Get-CimInstance -ClassName CIM_ComputerSystem).Model -notmatch "Virtual") { # Checking whether a WDDM verion is 2.7 or higher $WddmVersion_Min = Get-ItemPropertyValue -Path HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers\FeatureSetUsage -Name WddmVersion_Min if ($WddmVersion_Min -ge 2700) { New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers" -Name HwSchMode -PropertyType DWord -Value 2 -Force } } } } # Turn off hardware-accelerated GPU scheduling. Restart needed function DisableGPUScheduling { New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers" -Name HwSchMode -PropertyType DWord -Value 1 -Force } #endregion Gaming #region Scheduled tasks <# Create a 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 #> function CreateCleanUpTask { 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) "Previous Installations", # Setup log files "Setup Log Files", # Temporary Setup Files "Temporary Setup Files", # Microsoft Defender "Windows Defender", # Windows upgrade log files "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()) [xml]$ToastTemplate = @" <toast launch="app-defined-string"> <visual> <binding template="ToastGeneric"> <text>$($Localization.CleanUpTaskToast)</text> </binding> </visual> </toast> "@ $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 -TypeName 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 -TypeName System.Diagnostics.Process $Process.StartInfo = $ProcessInfo # Start the process $Process.Start() | Out-Null ' # Encode $PS1Script variable to be able to pipeline it as an argument $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 $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 a task to clean up unused files and Windows updates in the Task Scheduler function DeleteCleanUpTask { Unregister-ScheduledTask -TaskName "Windows Cleanup" -Confirm:$false } # Create a task to clear the %SystemRoot%\SoftwareDistribution\Download folder in the Task Scheduler # The task runs on Thursdays every 4 weeks function CreateSoftwareDistributionTask { $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.SoftwareDistributionTaskDescription $Parameters = @{ "TaskName" = "SoftwareDistribution" "TaskPath" = "Sophia Script" "Principal" = $Principal "Action" = $Action "Description" = $Description "Settings" = $Settings "Trigger" = $Trigger } Register-ScheduledTask @Parameters -Force } # Delete a task to clear the %SystemRoot%\SoftwareDistribution\Download folder in the Task Scheduler function DeleteCSoftwareDistributionTask { Unregister-ScheduledTask -TaskName SoftwareDistribution -Confirm:$false } # Create a task to clear the %TEMP% folder in the Task Scheduler # The task runs every 62 days function CreateTempTask { $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.TempTaskDescription $Parameters = @{ "TaskName" = "Temp" "TaskPath" = "Sophia Script" "Principal" = $Principal "Action" = $Action "Description" = $Description "Settings" = $Settings "Trigger" = $Trigger } Register-ScheduledTask @Parameters -Force } # Delete a task to clear the %TEMP% folder in the Task Scheduler function DeleteTempTask { Unregister-ScheduledTask -TaskName Temp -Confirm:$false } #endregion Scheduled tasks #region Microsoft Defender & Security # Enable Controlled folder access and add protected folders function AddProtectedFolders { $Title = $Localization.AddProtectedFoldersTitle $Message = $Localization.AddProtectedFoldersRequest $Add = $Localization.AddProtectedFoldersAdd $Skip = $Localization.AddProtectedFoldersSkip $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.AddProtectedFoldersDescription $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 Write-Verbose -Message ("{0}" -f $FolderBrowserDialog.SelectedPath) -Verbose } } "1" { Write-Verbose -Message $Localization.AddProtectedFoldersSkipped -Verbose } } } until ($Result -eq 1) } # Remove all added protected folders function RemoveProtectedFolders { if ($null -ne (Get-MpPreference).ControlledFolderAccessProtectedFolders) { Write-Verbose -Message $Localization.RemoveProtectedFoldersList -Verbose (Get-MpPreference).ControlledFolderAccessProtectedFolders | Format-Table -AutoSize -Wrap Remove-MpPreference -ControlledFolderAccessProtectedFolders (Get-MpPreference).ControlledFolderAccessProtectedFolders -Force } } # Allow an app through Controlled folder access function AddAppControlledFolder { $Title = $Localization.AddAppControlledFolderTitle $Message = $Localization.AddAppControlledFolderRequest $Add = $Localization.AddAppControlledFolderAdd $Skip = $Localization.AddAppControlledFolderSkip $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.AddAppControlledFolderFilter $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 Write-Verbose -Message ("{0}" -f $OpenFileDialog.FileName) -Verbose } } "1" { Write-Verbose -Message $Localization.AddAppControlledFolderSkipped -Verbose } } } until ($Result -eq 1) } # Remove all allowed apps through Controlled folder access function RemoveAllowedAppsControlledFolder { if ($null -ne (Get-MpPreference).ControlledFolderAccessAllowedApplications) { Write-Verbose -Message $Localization.RemoveAllowedAppsControlledFolderList -Verbose (Get-MpPreference).ControlledFolderAccessAllowedApplications | Format-Table -AutoSize -Wrap Remove-MpPreference -ControlledFolderAccessAllowedApplications (Get-MpPreference).ControlledFolderAccessAllowedApplications -Force } } # Add a folder to the exclusion from Microsoft Defender scanning function AddDefenderExclusionFolder { $Title = $Localization.AddDefenderExclusionFolderTitle $Message = $Localization.AddDefenderExclusionFolderRequest $Add = $Localization.AddDefenderExclusionFolderAdd $Skip = $Localization.AddDefenderExclusionFolderSkip $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.AddDefenderExclusionFolderDescription $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 Write-Verbose -Message ("{0}" -f $FolderBrowserDialog.SelectedPath) -Verbose } } "1" { Write-Verbose -Message $Localization.AddDefenderExclusionFolderSkipped -Verbose } } } until ($Result -eq 1) } # Remove all excluded folders from Microsoft Defender scanning function RemoveDefenderExclusionFolders { if ($null -ne (Get-MpPreference).ExclusionPath) { Write-Verbose -Message $Localization.RemoveDefenderExclusionFoldersList -Verbose $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 } } # Add a file to the exclusion from Microsoft Defender scanning function AddDefenderExclusionFile { $Title = $Localization.AddDefenderExclusionFileTitle $Message = $Localization.AddDefenderExclusionFileRequest $Add = $Localization.AddDefenderExclusionFileAdd $Skip = $Localization.AddDefenderExclusionFileSkip $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.AddDefenderExclusionFileFilter $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 Write-Verbose -Message ("{0}" -f $OpenFileDialog.FileName) -Verbose } } "1" { Write-Verbose -Message $Localization.AddDefenderExclusionFileSkipped -Verbose } } } until ($Result -eq 1) } # Remove all excluded files from Microsoft Defender scanning function RemoveDefenderExclusionFiles { if ($null -ne (Get-MpPreference).ExclusionPath) { Write-Verbose -Message $Localization.RemoveDefenderExclusionFilesList -Verbose $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 } } # Turn on Microsoft Defender Exploit Guard network protection function EnableNetworkProtection { Set-MpPreference -EnableNetworkProtection Enabled } # Turn off Microsoft Defender Exploit Guard network protection function DisableNetworkProtection { Set-MpPreference -EnableNetworkProtection Disabled } # Turn on detection for potentially unwanted applications and block them function EnablePUAppsDetection { Set-MpPreference -PUAProtection Enabled } # Turn off detection for potentially unwanted applications and block them function DisabledPUAppsDetection { Set-MpPreference -PUAProtection Disabled } # Run Microsoft Defender within a sandbox { setx /M MP_FORCE_USE_SANDBOX 1 } # Do not run Microsoft Defender within a sandbox function DisableDefenderSandbox { setx /M MP_FORCE_USE_SANDBOX 0 } # Dismiss Microsoft Defender offer in the Windows Security about signing in Microsoft account 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 function DismissSmartScreenFilter { New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows Security Health\State" -Name AppAndBrowser_EdgeSmartScreenOff -PropertyType DWord -Value 0 -Force } # Turn on events auditing generated when a process is created or starts function EnableAuditProcess { auditpol /set /subcategory:"{0CCE922B-69AE-11D9-BED3-505054503030}" /success:enable /failure:enable } # Turn off events auditing generated when a process is created or starts function DisableAuditProcess { auditpol /set /subcategory:"{0CCE922B-69AE-11D9-BED3-505054503030}" /success:disable /failure:disable } # Include command line in process creation events # In order this feature to work events auditing must be enabled ("EnableAuditProcess" function) function EnableAuditCommandLineProcess { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit -Name ProcessCreationIncludeCmdLine_Enabled -PropertyType DWord -Value 1 -Force } # Do not include command line in process creation events function DisableAuditCommandLineProcess { Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit -Name ProcessCreationIncludeCmdLine_Enabled -Force -ErrorAction SilentlyContinue } # 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 ("EnableAuditProcess" function) function CreateEventViewerCustomView { $XML = @" <ViewerConfig> <QueryConfig> <QueryParams> <UserQuery /> </QueryParams> <QueryNode> <Name>$($Localization.EventViewerCustomViewName)</Name> <Description>$($Localization.EventViewerCustomViewDescription)</Description> <QueryList> <Query Id="0" Path="Security"> <Select Path="Security">*[System[(EventID=4688)]]</Select> </Query> </QueryList> </QueryNode> </QueryConfig> </ViewerConfig> "@ 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 Set-Content -Path "$env:ProgramData\Microsoft\Event Viewer\Views\ProcessCreation.xml" -Value (New-Object -TypeName System.Text.UTF8Encoding).GetBytes($XML) -Encoding Byte -Force } # Remove "Process Creation" Event Viewer Custom View function RemoveEventViewerCustomView { Remove-Item -Path "$env:ProgramData\Microsoft\Event Viewer\Views\ProcessCreation.xml" -Force -ErrorAction SilentlyContinue } # Log for all Windows PowerShell modules function EnablePowerShellModulesLogging { 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 } # Do not log for all Windows PowerShell modules function DisablePowerShellModulesLogging { 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 } # Log all PowerShell scripts input to the Windows PowerShell event log function EnablePowerShellScriptsLogging { 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 } # Do not log all PowerShell scripts input to the Windows PowerShell event log function DisablePowerShellScriptsLogging { Remove-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging -Name EnableScriptBlockLogging -Force -ErrorAction SilentlyContinue } # Do not check apps and files within Microsofot Defender SmartScreen function DisableAppsSmartScreen { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name SmartScreenEnabled -PropertyType String -Value Off -Force } # Check apps and files within Microsofot Defender SmartScreen function EnableAppsSmartScreen { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name SmartScreenEnabled -PropertyType String -Value Warn -Force } # Prevent SmartScreen from marking files that have been downloaded from the Internet as unsafe (current user only) function DisableSaveZoneInformation { 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 } # Mark files that have been downloaded from the Internet as unsafe within SmartScreen (current user only) function EnableSaveZoneInformation { Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Attachments -Name SaveZoneInformation -Force -ErrorAction SilentlyContinue } # Turn off Windows Script Host (current user only) function DisableWindowsScriptHost { 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 } # Turn on Windows Script Host (current user only) function EnableWindowsScriptHost { Remove-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows Script Host\Settings" -Name Enabled -Force -ErrorAction SilentlyContinue } #endregion Microsoft Defender & Security #region Context menu # Add the "Extract all" item to Windows Installer (.msi) context menu function AddMSIExtractContext { 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 } # Remove the "Extract all" item from Windows Installer (.msi) context menu function RemoveMSIExtractContext { Remove-Item -Path Registry::HKEY_CLASSES_ROOT\Msi.Package\shell\Extract -Recurse -Force -ErrorAction SilentlyContinue } # Add the "Install" item to the .cab archives context menu function AddCABInstallContext { 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 } # Remove the "Install" item from the .cab archives context menu function RemoveCABInstallContext { Remove-Item -Path Registry::HKEY_CLASSES_ROOT\CABFolder\Shell\RunAs\Command -Recurse -Force -ErrorAction SilentlyContinue } # Add the "Run as different user" item to the .exe files types context menu function AddExeRunAsDifferentUserContext { Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\exefile\shell\runasuser -Name Extended -Force -ErrorAction Ignore } # Remove the "Run as different user" item from the .exe files types context menu function RemoveExeRunAsDifferentUserContext { New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\exefile\shell\runasuser -Name Extended -PropertyType String -Value "" -Force } # Hide the "Cast to Device" item from the context menu function HideCastToDeviceContext { 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 the "Cast to Device" item in the context menu function ShowCastToDeviceContext { Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Name "{7AD84985-87B4-4a16-BE58-8B72A5B390F7}" -Force -ErrorAction SilentlyContinue } # Hide the "Share" item from the context menu function HideShareContext { 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 the "Share" item in the context menu function ShowShareContext { Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked" -Name "{E2BF9676-5F8F-435C-97EB-11607A5BEDF7}" -Force -ErrorAction SilentlyContinue } # Hide the "Edit with Paint 3D" item from the context menu function HideEditWithPaint3DContext { $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 the "Edit with Paint 3D" item in the context menu function ShowEditWithPaint3DContext { $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 } } # Hide the "Edit with Photos" item from the context menu function HideEditWithPhotosContext { if (Get-AppxPackage -Name Microsoft.Windows.Photos) { New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\AppX43hnxtbyyps62jhe9sqpdzxn1790zetc\Shell\ShellEdit -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force } } # Show the "Edit with Photos" item in the context menu function ShowEditWithPhotosContext { if (Get-AppxPackage -Name Microsoft.Windows.Photos) { Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\AppX43hnxtbyyps62jhe9sqpdzxn1790zetc\Shell\ShellEdit -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue } } # Hide the "Create a new video" item from the context menu function HideCreateANewVideoContext { if (Get-AppxPackage -Name Microsoft.Windows.Photos) { New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\AppX43hnxtbyyps62jhe9sqpdzxn1790zetc\Shell\ShellCreateVideo -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force } } # Show the "Create a new video" item in the context menu function ShowCreateANewVideoContext { if (Get-AppxPackage -Name Microsoft.Windows.Photos) { Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\AppX43hnxtbyyps62jhe9sqpdzxn1790zetc\Shell\ShellCreateVideo -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue } } # Hide the "Edit" item from the images context menu function HideImagesEditContext { if ((Get-WindowsCapability -Online -Name "Microsoft.Windows.MSPaint*").State -eq "Installed") { New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\SystemFileAssociations\image\shell\edit -Name ProgrammaticAccessOnly -PropertyType String -Value "" -Force } } # Show the "Edit" item from in images context menu function ShowImagesEditContext { if ((Get-WindowsCapability -Online -Name "Microsoft.Windows.MSPaint*").State -eq "Installed") { Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\SystemFileAssociations\image\shell\edit -Name ProgrammaticAccessOnly -Force -ErrorAction SilentlyContinue } } # Hide the "Print" item from the .bat and .cmd context menu function HidePrintCMDContext { 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 the "Print" item in the .bat and .cmd context menu function ShowPrintCMDContext { 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 } # Hide the "Include in Library" item from the context menu function HideIncludeInLibraryContext { New-ItemProperty -Path "Registry::HKEY_CLASSES_ROOT\Folder\shellex\ContextMenuHandlers\Library Location" -Name "(Default)" -PropertyType String -Value "-{3dad6c5d-2167-4cae-9914-f99e41c12cfa}" -Force } # Show the "Include in Library" item in the context menu function ShowIncludeInLibraryContext { New-ItemProperty -Path "Registry::HKEY_CLASSES_ROOT\Folder\shellex\ContextMenuHandlers\Library Location" -Name "(Default)" -PropertyType String -Value "{3dad6c5d-2167-4cae-9914-f99e41c12cfa}" -Force } # Hide the "Send to" item from the folders context menu function HideSendToContext { New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\SendTo -Name "(Default)" -PropertyType String -Value "-{7BA4C740-9E81-11CF-99D3-00AA004AE837}" -Force } # Show the "Send to" item in the folders context menu function ShowSendToContext { New-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\SendTo -Name "(Default)" -PropertyType String -Value "{7BA4C740-9E81-11CF-99D3-00AA004AE837}" -Force } # Hide the "Turn on BitLocker" item from the context menu function HideBitLockerContext { 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 the "Turn on BitLocker" item in the context menu function ShowBitLockerContext { 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 } } # Remove the "Bitmap image" item from the "New" context menu function RemoveBitmapImageNewContext { if ((Get-WindowsCapability -Online -Name "Microsoft.Windows.MSPaint*").State -eq "Installed") { Remove-Item -Path Registry::HKEY_CLASSES_ROOT\.bmp\ShellNew -Force -ErrorAction SilentlyContinue } } # Restore the "Bitmap image" item in the "New" context menu function RestoreBitmapImageNewContext { 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 } } # Remove the "Rich Text Document" item from the "New" context menu function RemoveRichTextDocumentNewContext { if ((Get-WindowsCapability -Online -Name "Microsoft.Windows.WordPad*").State -eq "Installed") { Remove-Item -Path Registry::HKEY_CLASSES_ROOT\.rtf\ShellNew -Force -ErrorAction Ignore } } # Restore the "Rich Text Document" item in the "New" context menu function RestoreRichTextDocumentNewContext { 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 } } # Remove the "Compressed (zipped) Folder" item from the "New" context menu function RemoveCompressedFolderNewContext { Remove-Item -Path Registry::HKEY_CLASSES_ROOT\.zip\CompressedFolder\ShellNew -Force -ErrorAction Ignore } # Restore the "Compressed (zipped) Folder" item from the "New" context menu function RestoreCompressedFolderNewContext { 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 } # Make the "Open", "Print", and "Edit" context menu items available, when more than 15 items selected function EnableMultipleInvokeContext { 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 function DisableMultipleInvokeContext { Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name MultipleInvokePromptMinimum -Force -ErrorAction SilentlyContinue } # Hide the "Look for an app in the Microsoft Store" item in the "Open with" dialog function DisableUseStoreOpenWith { 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 the "Look for an app in the Microsoft Store" item in the "Open with" dialog function EnableUseStoreOpenWith { Remove-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name NoUseStoreOpenWith -Force -ErrorAction SilentlyContinue } # Hide the "Previous Versions" tab from files and folders context menu and also the "Restore previous versions" context menu item function DisablePreviousVersionsPage { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer -Name NoPreviousVersionsPage -PropertyType DWord -Value 1 -Force } # Show the "Previous Versions" tab from files and folders context menu and also the "Restore previous versions" context menu item function EnablePreviousVersionsPage { 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 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 PostMessageW(hWnd, Msg, UIntPtr, IntPtr.Zero); } "@ } if (-not ("WinAPI.UpdateExplorer" -as [type])) { Add-Type @UpdateExplorer } # Simulate pressing F5 to refresh the desktop [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() } }
@{
	RootModule        = 'Sophia.psm1'
	ModuleVersion     = '5.1.1'
	GUID              = '109cc881-c42b-45af-a74a-550781989d6a'
	Author            = 'Dmitry "farag" Nefedov'
	Copyright         = '(c) 2015–2020 farag & oZ-Zo. All rights reserved.'
	Description       = 'Module for Windows 10 fine-tuning and automating the routine tasks'
	PowerShellVersion = '5.1'
	ProcessorArchitecture = 'AMD64'
	FunctionsToExport = '*'

	PrivateData = @{
		PSData = @{
			LicenseUri   = 'https://github.com/farag2/Windows-10-Sophia-Script/blob/master/LICENSE'
			ProjectUri   = 'https://github.com/farag2/Windows-10-Sophia-Script'
			ReleaseNotes = 'https://github.com/farag2/Windows-10-Sophia-Script/blob/master/.github/CHANGELOG.md'
		}
	}
}
<#
	.SYNOPSIS
	Default preset file for "Windows 10 Sophia Script"

	Version: v5.1.1
	Date: 09.10.2020
	Copyright (c) 2020 farag & oZ-Zo

	.DESCRIPTION
	Supported Windows 10 versions: 2004 (20H1)/2009 (20H2), 19041/19042, Home/Pro/Enterprise, x64

	Due to the fact that the script includes more than 270 functions, you must read the entire preset file carefully
	and comment out/uncomment those functions that you do/do not want to be executed
	Every tweak in a preset file has its' corresponding function to restore the default settings

	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
	http://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/
	    
[PowerShell Script] Setup Windows 10 from PowerShell
.LINK https://github.com/farag2/Windows-10-Sophia-Script #> #Requires -RunAsAdministrator #Requires -Version 5.1 Clear-Host Remove-Module -Name Sophia -Force -ErrorAction Ignore Import-Module -Name .\Sophia.psd1 -PassThru -Force Import-LocalizedData -BindingVariable Global:Localization # Checking Check # Create a restore point CreateRestorePoint #region Privacy & Telemetry # Disable the "Connected User Experiences and Telemetry" service (DiagTrack) DisableTelemetryServices # Enable the "Connected User Experiences and Telemetry" service (DiagTrack) # EnableTelemetryServices # Set the OS level of diagnostic data gathering to minimum SetMinimalDiagnosticDataLevel # Set the default OS level of diagnostic data gathering # SetDefaultDiagnosticDataLevel # Turn off Windows Error Reporting for the current user DisableWindowsErrorReporting # Turn on Windows Error Reporting for the current user # EnableWindowsErrorReporting # Change Windows feedback frequency to "Never" for the current user DisableWindowsFeedback # Change Windows Feedback frequency to "Automatically" for the current user # EnableWindowsFeedback # Turn off diagnostics tracking scheduled tasks DisableScheduledTasks # Turn on diagnostics tracking scheduled tasks # EnableScheduledTasks # Do not use sign-in info to automatically finish setting up device and reopen apps after an update or restart (current user only) DisableSigninInfo # Use sign-in info to automatically finish setting up device and reopen apps after an update or restart (current user only) # EnableSigninInfo # Do not let websites provide locally relevant content by accessing language list (current user only) DisableLanguageListAccess # Let websites provide locally relevant content by accessing language list (current user only) # EnableLanguageListAccess # Do not allow apps to use advertising ID (current user only) DisableAdvertisingID # Allow apps to use advertising ID (current user only) # EnableAdvertisingID # Do not let apps on other devices open and message apps on this device, and vice versa (current user only) DisableShareAcrossDevices # Let apps on other devices open and message apps on this device, and vice versa (current user only) # EnableShareAcrossDevices # Do not show the Windows welcome experiences after updates and occasionally when I sign in to highlight what's new and suggested (current user only) DisableWindowsWelcomeExperience # Show the Windows welcome experiences after updates and occasionally when I sign in to highlight what's new and suggested (current user only) # EnableWindowsWelcomeExperience # Get tip, trick, and suggestions as you use Windows (current user only) EnableWindowsTips # Do not get tip, trick, and suggestions as you use Windows (current user only) # DisableWindowsTips # Do not show suggested content in the Settings app (current user only) DisableSuggestedContent # Show suggested content in the Settings app (current user only) # EnableSuggestedContent # Turn off automatic installing suggested apps (current user only) DisableAppsSilentInstalling # Turn on automatic installing suggested apps (current user only) # EnableAppsSilentInstalling # Do not suggest ways I can finish setting up my device to get the most out of Windows (current user only) DisableWhatsNewInWindows # Suggest ways I can finish setting up my device to get the most out of Windows # EnableWhatsNewInWindows # Do not offer tailored experiences based on the diagnostic data setting (current user only) DisableTailoredExperiences # Offer tailored experiences based on the diagnostic data setting # EnableTailoredExperiences # Disable Bing search in the Start Menu DisableBingSearch # Enable Bing search in the Start Menu # EnableBingSearch #endregion Privacy & Telemetry #region UI & Personalization # Show "This PC" on Desktop (current user only) ShowThisPC # Do not show "This PC" on Desktop (current user only) # HideThisPC # Do not use check boxes to select items (current user only) DisableCheckBoxes # Use check boxes to select items (current user only) # EnableCheckBoxes # Show hidden files, folders, and drives (current user only) ShowHiddenItems # Do not show hidden files, folders, and drives (current user only) # HideHiddenItems # Show file name extensions (current user only) ShowFileExtensions # Do not show file name extensions (current user only) # HideFileExtensions # Do not hide folder merge conflicts (current user only) ShowMergeConflicts # Hide folder merge conflicts (current user only) # HideMergeConflicts # Open File Explorer to: "This PC" (current user only) OpenFileExplorerToThisPC # Open File Explorer to: "Quick access" (current user only) # OpenFileExplorerToQuickAccess # Do not show Cortana button on the taskbar (current user only) HideCortanaButton # Show Cortana button on the taskbar (current user only) # ShowCortanaButton # Do not show sync provider notification within File Explorer (current user only) HideOneDriveFileExplorerAd # Show sync provider notification within File Explorer (current user only) # ShowOneDriveFileExplorerAd # Do not show Task View button on the taskbar (current user only) HideTaskViewButton # Show Task View button on the taskbar (current user only) # ShowTaskViewButton # Do not show People button on the taskbar (current user only) HidePeopleTaskbar # Show People button on the taskbar (current user only) # ShowPeopleTaskbar # Show seconds on the taskbar clock (current user only) ShowSecondsInSystemClock # Do not show seconds on the taskbar clock (current user only) # HideSecondsInSystemClock # Do not show when snapping a window, what can be attached next to it (current user only) DisableSnapAssist # Show when snapping a window, what can be attached next to it (current user only) # EnableSnapAssist # Always open the file transfer dialog box in the detailed mode (current user only) FileTransferDialogDetailed # Always open the file transfer dialog box in the compact mode (current user only) # FileTransferDialogCompact # Show the ribbon expanded in File Explorer (current user only) FileExplorerRibbonExpanded # Do not show the ribbon expanded in File Explorer (current user only) # FileExplorerRibbonMinimized # Display recycle bin files delete confirmation EnableRecycleBinDeleteConfirmation # Do not display recycle bin files delete confirmation # DisableRecycleBinDeleteConfirmation # Hide the "3D Objects" folder from "This PC" and "Quick access" (current user only) Hide3DObjects # Show the "3D Objects" folder from "This PC" and "Quick access" (current user only) # Show3DObjects # Do not show frequently used folders in "Quick access" (current user only) HideQuickAccessFrequentFolders # Show frequently used folders in "Quick access" (current user only) # ShowQuickAccessFrequentFolders # Do not show recently used files in Quick access (current user only) HideQuickAccessRecentFiles # Show recently used files in Quick access (current user only) # ShowQuickAccessShowRecentFiles # Hide the search box or the search icon from the taskbar (current user only) HideTaskbarSearch # Show the search box from the taskbar (current user only) # ShowTaskbarSearch # Do not show the "Windows Ink Workspace" button on the taskbar (current user only) HideWindowsInkWorkspace # Show the "Windows Ink Workspace" button in taskbar (current user only) # ShowWindowsInkWorkspace # Always show all icons in the notification area (current user only) ShowTrayIcons # Do not show all icons in the notification area (current user only) # HideTrayIcons # Unpin "Microsoft Edge" and "Microsoft Store" from the taskbar (current user only) UnpinTaskbarEdgeStore # View the Control Panel icons by: large icons (current user only) ControlPanelLargeIcons # View the Control Panel icons by: category (current user only) # ControlPanelCategoryIcons # Set the Windows mode color scheme to the light (current user only) # WindowsColorSchemeLight # Set the Windows mode color scheme to the dark (current user only) WindowsColorSchemeDark # Set the default app mode color scheme to the light (current user only) # AppModeLight # Set the default app mode color scheme to the dark (current user only) AppModeDark # Do not show the "New App Installed" indicator DisableNewAppInstalledNotification # Show the "New App Installed" indicator # EnableNewAppInstalledNotification # Do not show user first sign-in animation after the upgrade HideFirstSigninAnimation # Show user first sign-in animation the upgrade # ShowFirstSigninAnimation # Set the quality factor of the JPEG desktop wallpapers to maximum (current user only) JPEGWallpapersQualityMax # Set the quality factor of the JPEG desktop wallpapers to default (current user only) # JPEGWallpapersQualityDefault # Start Task Manager in expanded mode (current user only) TaskManagerWindowExpanded # Start Task Manager in compact mode (current user only) # TaskManagerWindowCompact # Show a notification when your PC requires a restart to finish updating ShowRestartNotification # Do not show a notification when your PC requires a restart to finish updating # HideRestartNotification # Do not add the "- Shortcut" suffix to the file name of created shortcuts (current user only) DisableShortcutsSuffix # Add the "- Shortcut" suffix to the file name of created shortcuts (current user only) # EnableShortcutsSuffix # Use the PrtScn button to open screen snipping (current user only) EnablePrtScnSnippingTool # Do not use the PrtScn button to open screen snipping (current user only) # DisablePrtScnSnippingTool #endregion UI & Personalization #region OneDrive # Uninstall OneDrive UninstallOneDrive # Install OneDrive (current user only) # InstallOneDrive #endregion OneDrive #region System # Turn on Storage Sense (current user only) EnableStorageSense # Turn off Storage Sense (current user only) # DisableStorageSense # Run Storage Sense every month (current user only) StorageSenseMonthFrequency # Run Storage Sense during low free disk space (default value) (current user only) # StorageSenseDefaultFrequency # Delete temporary files that apps aren't using (current user only) EnableStorageSenseTempFiles # Do not delete temporary files that apps aren't using (current user only) # DisableStorageSenseTempFiles # Delete files in recycle bin if they have been there for over 30 days (current user only) EnableStorageSenseRecycleBin # Do not delete files in recycle bin if they have been there for over 30 days (current user only) # DisableStorageSenseRecycleBin # Disable hibernation if the device is not a laptop DisableHibernate # Turn on hibernate # EnableHibernate # Change the %TEMP% environment variable path to the %SystemDrive%\Temp (both machine-wide, and for the current user) SetTempPath # Change %TEMP% environment variable path to the %LOCALAPPDATA%\Temp (default value) (both machine-wide, and for the current user) # SetDefaultTempPath # Enable Windows 260 character path limit EnableWin32LongPaths # Disable Windows 260 character path limit # DisableWin32LongPaths # Display the Stop error information on the BSoD EnableBSoDStopError # Do not display the Stop error information on the BSoD # DisableBSoDStopError # Change "Behavior of the elevation prompt for administrators in Admin Approval Mode" to "Elevate without prompting" DisableAdminApprovalMode # Change "Behavior of the elevation prompt for administrators in Admin Approval Mode" to "Prompt for consent for non-Windows binaries" (default value) # EnableAdminApprovalMode # Turn on access to mapped drives from app running with elevated permissions with Admin Approval Mode enabled EnableMappedDrivesAppElevatedAccess # Turn off access to mapped drives from app running with elevated permissions with Admin Approval Mode enabled # DisableMappedDrivesAppElevatedAccess # Opt out of the Delivery Optimization-assisted updates downloading DisableDeliveryOptimization # Opt-in to the Delivery Optimization-assisted updates downloading # EnableDeliveryOptimization # Always wait for the network at computer startup and logon for workgroup networks AlwaysWaitNetworkStartup # Never wait for the network at computer startup and logon for workgroup networks # NeverWaitNetworkStartup # Do not let Windows decide which printer should be the default one (current user only) DisableWindowsManageDefaultPrinter # Let Windows decide which printer should be the default one (current user only) # EnableWindowsManageDefaultPrinter # Disable the following Windows features DisableWindowsFeatures # Enable the following Windows features # EnableWindowsFeatures <# Install the Windows Subsystem for Linux (WSL) https://github.com/farag2/Windows-10-Setup-Script/issues/43 https://github.com/microsoft/WSL/issues/5437 #> # InstallWSL <# Download and install the Linux kernel update package Set WSL 2 as the default version when installing a new Linux distribution Run the function only after WSL installed and PC restart https://github.com/microsoft/WSL/issues/5437 #> # SetupWSL <# Disable swap file in WSL Use only if the %TEMP% environment variable path changed https://github.com/microsoft/WSL/issues/5437 #> # DisableWSLSwap <# Enable swap file in WSL https://github.com/microsoft/WSL/issues/5437 #> # EnableWSLSwap # Uninstall the Windows Subsystem for Linux (WSL2) # UninstallWSL # Disable certain Feature On Demand v2 (FODv2) capabilities DisableWindowsCapabilities # Opt-in to Microsoft Update service, so to receive updates for other Microsoft products EnableUpdatesMicrosoftProducts # Opt-out of Microsoft Update service, so not to receive updates for other Microsoft products # DisableUpdatesMicrosoftProducts # Do not let UWP apps run in the background, except the followings... (current user only) DisableBackgroundUWPApps # Let UWP apps run in the background (current user only) # EnableBackgroundUWPApps # Set the power management scheme on "High performance" if device is a desktop DesktopPowerManagementScheme # Set the power management scheme on "Balanced" (default value) # DefaultPowerManagementScheme # Use latest installed .NET runtime for all apps EnableLatestInstalled.NET # Do not use latest installed .NET runtime for all apps # DisableLatestInstalled.NET # Do not allow the computer (if device is not a laptop) to turn off the network adapters to save power DisallowPCTurnOffDevice # Allow the computer to turn off the network adapters to save power # AllowPCTurnOffDevice # Set the default input method to the English language SetEnglishDefaultInputMethod # Reset the default input method # ResetDefaultInputMethod # Enable Windows Sandbox EnableWindowsSandbox # Disable Windows Sandbox # DisableWindowsSandbox <# Change the location of the user folders to any drives root (current user only) It is suggested to move it to any disks root of your choice using the interactive menu by default User files or folders won't me moved to a new location #> ChangeUserShellFolderLocation <# 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 #> # SetDefaultUserShellFolderLocation # Save screenshots by pressing Win+PrtScr to the Desktop folder (current user only) WinPrtScrDesktopFolder # Save screenshots by pressing Win+PrtScr to the Pictures folder (default value) (current user only) # WinPrtScrDefaultFolder <# Run troubleshooters automatically, then notify In order this feature to work the OS level of diagnostic data gathering must be set to "Full" #> AutomaticRecommendedTroubleshooting <# Ask me before running troubleshooters (default value) In order this feature to work the OS level of diagnostic data gathering must be set to "Full" #> # DefaultRecommendedTroubleshooting # Launch folder windows in a separate process (current user only) EnableFoldersLaunchSeparateProcess # Do not folder windows in a separate process (current user only) # DisableFoldersLaunchSeparateProcess # Disable and delete reserved storage after the next update installation DisableReservedStorage # Turn on reserved storage # EnableReservedStorage # Disable help lookup via F1 (current user only) DisableF1HelpPage # Turn on Help page opening by F1 key (current user only) # EnableF1HelpPage # Turn on Num Lock at startup EnableNumLock # Turn off Num Lock at startup # DisableNumLock # Do not activate StickyKey after tapping the Shift key 5 times (current user only) DisableStickyShift # Activate StickyKey after tapping the Shift key 5 times (current user only) # EnableStickyShift # Do not use AutoPlay for all media and devices (current user only) DisableAutoplay # Use AutoPlay for all media and devices (current user only) # EnableAutoplay # Disable thumbnail cache removal DisableThumbnailCacheRemoval # Enable thumbnail cache removal # EnableThumbnailCacheRemoval # Automatically save my restartable apps when signing out and restart them after signing in (current user only) EnableSaveRestartableApps # Do not automatically save my restartable apps when signing out and restart them after signing in # DisableSaveRestartableApps # Enable "Network Discovery" and "File and Printers Sharing" for workgroup networks EnableNetworkDiscovery # Disable "Network Discovery" and "File and Printers Sharing" for workgroup networks # DisableNetworkDiscovery # Automatically adjust active hours for me based on daily usage EnableSmartActiveHours # Do not automatically adjust active hours for me based on daily usage # DisableSmartActiveHours # Restart this device as soon as possible when a restart is required to install an update EnableDeviceRestartAfterUpdate # Do not restart this device as soon as possible when a restart is required to install an update # DisableDeviceRestartAfterUpdate #endregion System #region Start menu # Do not show recently added apps in the Start menu HideRecentlyAddedApps # Show recently added apps in the Start menu # ShowRecentlyAddedApps # Do not show app suggestions in the Start menu HideAppSuggestions # Show app suggestions in the Start menu # ShowAppSuggestions # Run the Command Prompt shortcut from the Start menu as Administrator RunCMDShortcutElevated # Run the Command Prompt shortcut from the Start menu as user # RunCMDShortcutUser # Unpin all the Start tiles UnpinAllStartTiles <# Pin the "Control Panel" shortcut to Start within syspin http://www.technosys.net/products/utils/pintotaskbar SHA256: 6967E7A3C2251812DD6B3FA0265FB7B61AADC568F562A98C50C345908C6E827 #> PinControlPanel <# Pin the old-style "Devices and Printers" shortcut to Start within syspin http://www.technosys.net/products/utils/pintotaskbar SHA256: 6967E7A3C2251812DD6B3FA0265FB7B61AADC568F562A98C50C345908C6E827 #> PinDevicesPrinters <# Pin the Command Prompt" shortcut to Start within syspin http://www.technosys.net/products/utils/pintotaskbar SHA256: 6967E7A3C2251812DD6B3FA0265FB7B61AADC568F562A98C50C345908C6E827 #> PinCommandPrompt #endregion Start menu #region UWP apps <# Uninstall UWP apps A dialog box that enables the user to select packages to remove App packages will not be installed for new users if "Uninstall for All Users" is checked #> UninstallUWPApps <# Open Microsoft Store "HEVC Video Extensions from Device Manufacturer" page The extension can be installed without Microsoft account for free instead of $0.99 "Movies & TV" app required #> InstallHEVC # Turn off Cortana autostarting DisableCortanaAutostart # Turn on Cortana autostarting # EnableCortanaAutostart # Check for UWP apps updates CheckUWPAppsUpdates #endregion UWP apps #region Gaming # Turn off Xbox Game Bar DisableXboxGameBar # Turn on Xbox Game Bar # EnableXboxGameBar # Turn off Xbox Game Bar tips DisableXboxGameTips # Turn on Xbox Game Bar tips # EnableXboxGameTips <# Set "High performance" in graphics performance preference for an app Only with a dedicated GPU #> SetAppGraphicsPerformance <# Turn on hardware-accelerated GPU scheduling. Restart needed Only with a dedicated GPU and WDDM verion is 2.7 or higher #> EnableGPUScheduling # Turn off hardware-accelerated GPU scheduling. Restart needed # DisableGPUScheduling #endregion Gaming #region Scheduled tasks <# Create a 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 #> CreateCleanUpTask # Delete a task to clean up unused files and Windows updates in the Task Scheduler # DeleteCleanUpTask # Create a task to clear the %SystemRoot%\SoftwareDistribution\Download folder in the Task Scheduler # The task runs on Thursdays every 4 weeks CreateSoftwareDistributionTask # Delete a task to clear the %SystemRoot%\SoftwareDistribution\Download folder in the Task Scheduler # DeleteCSoftwareDistributionTask # Create a task to clear the %TEMP% folder in the Task Scheduler # The task runs every 62 days CreateTempTask # Delete a task to clear the %TEMP% folder in the Task Scheduler # DeleteTempTask #endregion Scheduled tasks #region Microsoft Defender & Security # Enable Controlled folder access and add protected folders AddProtectedFolders # Remove all added protected folders # RemoveProtectedFolders # Allow an app through Controlled folder access AddAppControlledFolder # Remove all allowed apps through Controlled folder access # RemoveAllowedAppsControlledFolder # Add a folder to the exclusion from Microsoft Defender scanning AddDefenderExclusionFolder # Remove all excluded folders from Microsoft Defender scanning # RemoveDefenderExclusionFolders # Add a file to the exclusion from Microsoft Defender scanning AddDefenderExclusionFile # Remove all excluded files from Microsoft Defender scanning # RemoveDefenderExclusionFiles # Turn on Microsoft Defender Exploit Guard network protection EnableNetworkProtection # Turn off Microsoft Defender Exploit Guard network protection # DisableNetworkProtection # Turn on detection for potentially unwanted applications and block them EnablePUAppsDetection # Turn off detection for potentially unwanted applications and block them # DisabledPUAppsDetection # Run Microsoft Defender within a sandbox EnableDefenderSandbox # Do not run Microsoft Defender within a sandbox # DisableDefenderSandbox # Dismiss Microsoft Defender offer in the Windows Security about signing in Microsoft account DismissMSAccount # Dismiss Microsoft Defender offer in the Windows Security about turning on the SmartScreen filter for Microsoft Edge DismissSmartScreenFilter # Turn on events auditing generated when a process is created or starts EnableAuditProcess # Turn off events auditing generated when a process is created or starts # DisableAuditProcess # Include command line in process creation events # In order this feature to work events auditing must be enabled ("EnableAuditProcess" function) EnableAuditCommandLineProcess # Do not include command line in process creation events # DisableAuditCommandLineProcess # 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 ("EnableAuditProcess" function) CreateEventViewerCustomView # Remove "Process Creation" Event Viewer Custom View # RemoveEventViewerCustomView # Log for all Windows PowerShell modules EnablePowerShellModulesLogging # Do not log for all Windows PowerShell modules # DisablePowerShellModulesLogging # Log all PowerShell scripts input to the Windows PowerShell event log EnablePowerShellScriptsLogging # Do not log all PowerShell scripts input to the Windows PowerShell event log # DisablePowerShellScriptsLogging # Do not check apps and files within Microsofot Defender SmartScreen DisableAppsSmartScreen # Check apps and files within Microsofot Defender SmartScreen # EnableAppsSmartScreen # Prevent SmartScreen from marking files that have been downloaded from the Internet as unsafe (current user only) DisableSaveZoneInformation # Mark files that have been downloaded from the Internet as unsafe within SmartScreen (current user only) # EnableSaveZoneInformation # Turn off Windows Script Host (current user only) DisableWindowsScriptHost # Turn on Windows Script Host (current user only) # EnableWindowsScriptHost #endregion Microsoft Defender & Security #region Context menu # Add the "Extract all" item to Windows Installer (.msi) context menu AddMSIExtractContext # Remove the "Extract all" item from Windows Installer (.msi) context menu # RemoveMSIExtractContext # Add the "Install" item to the .cab archives context menu AddCABInstallContext # Remove the "Install" item from the .cab archives context menu # RemoveCABInstallContext # Add the "Run as different user" item to the .exe files types context menu AddExeRunAsDifferentUserContext # Remove the "Run as different user" item from the .exe files types context menu # RemoveExeRunAsDifferentUserContext # Hide the "Cast to Device" item from the context menu HideCastToDeviceContext # Show the "Cast to Device" item in the context menu # ShowCastToDeviceContext # Hide the "Share" item from the context menu HideShareContext # Show the "Share" item in the context menu # ShowShareContext # Hide the "Edit with Paint 3D" item from the context menu HideEditWithPaint3DContext # Show the "Edit with Paint 3D" item in the context menu # ShowEditWithPaint3DContext # Hide the "Edit with Photos" item from the context menu HideEditWithPhotosContext # Show the "Edit with Photos" item in the context menu # ShowEditWithPhotosContext # Hide the "Create a new video" item from the context menu HideCreateANewVideoContext # Show the "Create a new video" item in the context menu # ShowCreateANewVideoContext # Hide the "Edit" item from the images context menu HideImagesEditContext # Show the "Edit" item from in images context menu # ShowImagesEditContext # Hide the "Print" item from the .bat and .cmd context menu HidePrintCMDContext # Show the "Print" item in the .bat and .cmd context menu # ShowPrintCMDContext # Hide the "Include in Library" item from the context menu HideIncludeInLibraryContext # Show the "Include in Library" item in the context menu # ShowIncludeInLibraryContext # Hide the "Send to" item from the folders context menu HideSendToContext # Show the "Send to" item in the folders context menu # ShowSendToContext # Hide the "Turn on BitLocker" item from the context menu HideBitLockerContext # Show the "Turn on BitLocker" item in the context menu # ShowBitLockerContext # Remove the "Bitmap image" item from the "New" context menu RemoveBitmapImageNewContext # Restore the "Bitmap image" item in the "New" context menu # RestoreBitmapImageNewContext # Remove the "Rich Text Document" item from the "New" context menu RemoveRichTextDocumentNewContext # Restore the "Rich Text Document" item in the "New" context menu # RestoreRichTextDocumentNewContext # Remove the "Compressed (zipped) Folder" item from the "New" context menu RemoveCompressedFolderNewContext # Restore the "Compressed (zipped) Folder" item from the "New" context menu # RestoreCompressedFolderNewContext # Make the "Open", "Print", and "Edit" context menu items available, when more than 15 items selected EnableMultipleInvokeContext # Disable the "Open", "Print", and "Edit" context menu items for more than 15 items selected # DisableMultipleInvokeContext # Hide the "Look for an app in the Microsoft Store" item in the "Open with" dialog DisableUseStoreOpenWith # Show the "Look for an app in the Microsoft Store" item in the "Open with" dialog # EnableUseStoreOpenWith # Hide the "Previous Versions" tab from files and folders context menu and also the "Restore previous versions" context menu item DisablePreviousVersionsPage # Show the "Previous Versions" tab from files and folders context menu and also the "Restore previous versions" context menu item # EnablePreviousVersionsPage #endregion Context menu <# Simulate pressing F5 to refresh the desktop Refresh desktop icons, environment variables, taskbar Restart the Start menu #> Refresh # Errors output Errors

Download from GitHub ^

Windows 10 Sophia Script

+3
avatar
1 Comment
  1. Leos Marek (Rank: 4)
    11 months ago

    Dmitry,

    that looks really cool! I will definitely try it out when I have the chance!

    cheers

    0

Leave a reply

Please enclose code in pre tags

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2021

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account