<# .SYNOPSIS Sophia Script is a PowerShell module for Windows 10 & Windows 11 fine-tuning and automating the routine tasks Version: v5.18.5 Date: 14.04.2024 Copyright (c) 2014—2024 farag, Inestic & lowl1f3 Thanks to all https://forum.ru-board.com members involved .NOTES Supported Windows 10 version Version: 21H2 Build: 19044.4291+ Edition: Enterprise LTSC 2021 Architecture: x64 .LINK GitHub https://github.com/farag2/Sophia-Script-for-Windows .LINK Telegram https://t.me/sophianews https://t.me/sophia_chat .LINK Discord https://discord.gg/sSryhaEv79 .NOTES https://forum.ru-board.com/topic.cgi?forum=62&topic=30617#15 https://habr.com/company/skillfactory/blog/553800/ https://forums.mydigitallife.net/threads/powershell-windows-10-sophia-script.81675/ https://www.reddit.com/r/PowerShell/comments/go2n5v/powershell_script_setup_windows_10/ .LINK Authors https://github.com/farag2 https://github.com/Inestic https://github.com/lowl1f3 #> #region InitialActions function InitialActions { param ( [Parameter(Mandatory = $false)] [switch] $Warning ) Set-StrictMode -Version Latest # Сlear the $Error variable $Global:Error.Clear() # Unblock all files in the script folder by removing the Zone.Identifier alternate data stream with a value of "3" Get-ChildItem -Path $PSScriptRoot\..\ -File -Recurse -Force | Unblock-File [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # Progress bar can significantly impact cmdlet performance # https://github.com/PowerShell/PowerShell/issues/2138 $Script:ProgressPreference = "SilentlyContinue" # Extract strings from %SystemRoot%\System32\shell32.dll using its number # https://github.com/SamuelArnold/StarKill3r/blob/master/Star%20Killer/Star%20Killer/bin/Debug/Scripts/SANS-SEC505-master/scripts/Day1-PowerShell/Expand-IndirectString.ps1 # [WinAPI.GetStrings]::GetIndirectString("@%SystemRoot%\system32\schedsvc.dll,-100") # https://github.com/PowerShell/PowerShell/issues/21070 $Script:CompilerParameters = [System.CodeDom.Compiler.CompilerParameters]::new("System.dll") $Script:CompilerParameters.TempFiles = [System.CodeDom.Compiler.TempFileCollection]::new($env:TEMP, $false) $Script:CompilerParameters.GenerateInMemory = $true $Signature = @{ Namespace = "WinAPI" Name = "GetStrings" Language = "CSharp" UsingNamespace = "System.Text" CompilerParameters = $CompilerParameters MemberDefinition = @" [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(); } // Get string from other DLLs [DllImport("shlwapi.dll", CharSet=CharSet.Unicode)] private static extern int SHLoadIndirectString(string pszSource, StringBuilder pszOutBuf, int cchOutBuf, string ppvReserved); public static string GetIndirectString(string indirectString) { try { int returnValue; StringBuilder lptStr = new StringBuilder(1024); returnValue = SHLoadIndirectString(indirectString, lptStr, 1024, null); if (returnValue == 0) { return lptStr.ToString(); } else { return null; // return "SHLoadIndirectString Failure: " + returnValue; } } catch // (Exception ex) { return null; // return "Exception Message: " + ex.Message; } } "@ } if (-not ("WinAPI.GetStrings" -as [type])) { Add-Type @Signature } $Signature = @{ Namespace = "WinAPI" Name = "ForegroundWindow" Language = "CSharp" CompilerParameters = $CompilerParameters MemberDefinition = @" [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); "@ } if (-not ("WinAPI.ForegroundWindow" -as [type])) { Add-Type @Signature } # Detect Windows bitness if (-not [System.Environment]::Is64BitOperatingSystem) { Write-Warning -Message $Localization.UnsupportedOSBitness Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } # Check the language mode if ($ExecutionContext.SessionState.LanguageMode -ne "FullLanguage") { Write-Warning -Message $Localization.UnsupportedLanguageMode Write-Verbose -Message "https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_language_modes" -Verbose Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } # Check whether the logged-in user is an admin $CurrentUserName = (Get-Process -Id $PID -IncludeUserName).UserName | Split-Path -Leaf $CurrentSessionId = (Get-Process -Id $PID -IncludeUserName).SessionId $LoginUserName = (Get-Process -IncludeUserName | Where-Object -FilterScript {($_.ProcessName -eq "explorer") -and ($_.SessionId -eq $CurrentSessionId)}).UserName | Select-Object -First 1 | Split-Path -Leaf if ($CurrentUserName -ne $LoginUserName) { Write-Warning -Message $Localization.LoggedInUserNotAdmin Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } # Check whether the script was run via PowerShell 5.1 if ($PSVersionTable.PSVersion.Major -ne 5) { Write-Warning -Message ($Localization.UnsupportedPowerShell -f $PSVersionTable.PSVersion.Major, $PSVersionTable.PSVersion.Minor) Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } # Check whether the script was run in PowerShell ISE or VS Code if (($Host.Name -match "ISE") -or ($env:TERM_PROGRAM -eq "vscode")) { Write-Warning -Message ($Localization.UnsupportedHost -f $Host.Name.Replace("Host", "")) Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } # Check whether Windows was broken by 3rd party harmful tweakers and trojans $Tweakers = @{ # https://github.com/Sycnex/Windows10Debloater Windows10Debloater = "$env:SystemDrive\Temp\Windows10Debloater" # https://github.com/Fs00/Win10BloatRemover Win10BloatRemover = "$env:TEMP\.net\Win10BloatRemover" # https://github.com/arcadesdude/BRU "Bloatware Removal" = "$env:SystemDrive\BRU\Bloatware-Removal*.log" # https://www.youtube.com/GHOSTSPECTRE "Ghost Toolbox" = "$env:SystemRoot\System32\migwiz\dlmanifests\run.ghost.cmd" # https://github.com/hellzerg/optimizer Optimizer = "$(Get-ItemPropertyValue -Path `"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders`" -Name `"{374DE290-123F-4565-9164-39C4925E467B}`")\OptimizerDownloads" # https://win10tweaker.ru "Win 10 Tweaker" = "HKCU:\Software\Win 10 Tweaker" # https://forum.ru-board.com/topic.cgi?forum=5&topic=50519 "Modern Tweaker" = "Registry::HKEY_CLASSES_ROOT\CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\shell\Modern Cleaner" # https://boosterx.ru BoosterX = "$env:ProgramFiles\GameModeX\GameModeX.exe" # https://forum.ru-board.com/topic.cgi?forum=5&topic=14285&start=400#11 "Defender Control" = "$env:APPDATA\Defender Control" # https://forum.ru-board.com/topic.cgi?forum=5&topic=14285&start=260#12 "Defender Switch" = "$env:ProgramData\DSW" # https://revi.cc/revios/download "Revision Tool" = "${env:ProgramFiles(x86)}\Revision Tool" # https://www.youtube.com/watch?v=L0cj_I6OF2o "WinterOS Tweaker" = "$env:SystemRoot\WinterOS*" # https://github.com/ThePCDuke/WinCry WinCry = "$env:SystemRoot\TempCleaner.exe" # https://hone.gg Hone = "$env:LOCALAPPDATA\Programs\Hone\Hone.exe" # https://github.com/ChrisTitusTech/winutil winutil = "$env:TEMP\Winutil.log" # https://www.youtube.com/watch?v=5NBqbUUB1Pk WinClean = "$env:ProgramFiles\WinClean Plus Apps" } foreach ($Tweaker in $Tweakers.Keys) { if (Test-Path -Path $Tweakers[$Tweaker]) { if ($Tweakers[$Tweaker] -eq "HKCU:\Software\Win 10 Tweaker") { Write-Warning -Message $Localization.Win10TweakerWarning Write-Verbose -Message "https://youtu.be/na93MS-1EkM" -Verbose Write-Verbose -Message "https://pikabu.ru/story/byekdor_v_win_10_tweaker_ili_sovremennyie_metodyi_borbyi_s_piratstvom_8227558" -Verbose Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } Write-Warning -Message ($Localization.TweakerWarning -f $Tweaker) Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } } # Check whether Windows was broken by 3rd party harmful tweakers and trojans $Tweakers = @{ # https://forum.ru-board.com/topic.cgi?forum=62&topic=30617&start=1600#14 AutoSettingsPS = "$(Get-Item -Path `"HKLM:\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths`" | Where-Object -FilterScript {$_.Property -match `"AutoSettingsPS`"})" # Flibustier custom Windows image Flibustier = "$(Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\.NETFramework\Performance -Name *flibustier)" } foreach ($Tweaker in $Tweakers.Keys) { if ($Tweakers[$Tweaker]) { Write-Warning -Message ($Localization.TweakerWarning -f $Tweaker) Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } } # Check whether Get-WindowsEdition cmdlet is working try { Get-WindowsEdition -Online } catch [System.Runtime.InteropServices.COMException] { Write-Warning -Message ($Localization.WindowsComponentBroken -f "Get-WindowsEdition") exit } # Check whether EventLog service is running in order to be sire that Event Logger is enabled if ((Get-Service -Name EventLog).Status -eq "Stopped") { # Extract the localized "Event Viewer" string from shell32.dll Write-Warning -Message ($Localization.WindowsComponentBroken -f $([WinAPI.GetStrings]::GetString(22029))) Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } #region Defender checks # Check whether necessary Microsoft Defender components exists $Files = @( "$env:SystemRoot\System32\smartscreen.exe", "$env:SystemRoot\System32\SecurityHealthSystray.exe", "$env:SystemRoot\System32\CompatTelRunner.exe" ) foreach ($File in $Files) { if (-not (Test-Path -Path $File)) { Write-Warning -Message ($Localization.WindowsComponentBroken -f $File) Write-Verbose -Message "https://github.com/farag2/Sophia-Script-for-Windows/releases/latest" -Verbose Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } } # Checking whether Windows Security Settings page was hidden from UI if ([Microsoft.Win32.Registry]::GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer", "SettingsPageVisibility", $null) -match "hide:windowsdefender") { Write-Warning -Message ($Localization.WindowsComponentBroken -f "Microsoft Defender") Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } # Checking whether WMI is corrupted try { Get-CimInstance -ClassName MSFT_MpComputerStatus -Namespace root/Microsoft/Windows/Defender -ErrorAction Stop | Out-Null } catch [Microsoft.Management.Infrastructure.CimException] { # Provider Load Failure exception Write-Warning -Message $Global:Error.Exception.Message | Select-Object -First 1 Write-Warning -Message ($Localization.WindowsComponentBroken -f "Microsoft Defender") Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } # Check Microsoft Defender state if ($null -eq (Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct -ErrorAction Ignore)) { Write-Warning -Message ($Localization.WindowsComponentBroken -f "Microsoft Defender") Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } # Checking services try { $Services = Get-Service -Name Windefend, SecurityHealthService, wscsvc -ErrorAction Stop Get-Service -Name SecurityHealthService -ErrorAction Stop | Start-Service } catch [Microsoft.PowerShell.Commands.ServiceCommandException] { Write-Warning -Message ($Localization.WindowsComponentBroken -f "Microsoft Defender") Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } $Script:DefenderServices = ($Services | Where-Object -FilterScript {$_.Status -ne "running"} | Measure-Object).Count -lt $Services.Count # Check Microsoft Defender state $productState = (Get-CimInstance -Namespace root/SecurityCenter2 -ClassName Antivirusproduct | Where-Object -FilterScript {$_.instanceGuid -eq "{D68DDC3A-831F-4fae-9E44-DA132C1ACF46}"}).productState $DefenderState = ('0x{0:x}' -f $productState).Substring(3, 2) if ($DefenderState -notmatch "00|01") { # Defender is a currently used AV. Continue... $Script:DefenderProductState = $true # Check whether Microsoft Defender was turned off via GPO # Due to "Set-StrictMode -Version Latest" we have to use GetValue() if ([Microsoft.Win32.Registry]::GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender", "DisableAntiSpyware", $null) -eq 1) { $Script:AntiSpywareEnabled = $false } else { $Script:AntiSpywareEnabled = $true } # Check whether Microsoft Defender was turned off via GPO # Due to "Set-StrictMode -Version Latest" we have to use GetValue() if ([Microsoft.Win32.Registry]::GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection", "DisableRealtimeMonitoring", $null) -eq 1) { $Script:RealtimeMonitoringEnabled = $false } else { $Script:RealtimeMonitoringEnabled = $true } # Check whether Microsoft Defender was turned off via GPO # Due to "Set-StrictMode -Version Latest" we have to use GetValue() if ([Microsoft.Win32.Registry]::GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection", "DisableBehaviorMonitoring", $null) -eq 1) { $Script:BehaviorMonitoringEnabled = $false } else { $Script:BehaviorMonitoringEnabled = $true } } else { $Script:DefenderProductState = $false } if ($Script:DefenderServices -and $Script:DefenderproductState -and $Script:AntiSpywareEnabled -and $Script:RealtimeMonitoringEnabled -and $Script:BehaviorMonitoringEnabled) { # Defender is enabled $Script:DefenderEnabled = $true switch ((Get-MpPreference).EnableControlledFolderAccess) { "1" { Write-Warning -Message $Localization.ControlledFolderAccessDisabled # Turn off Controlled folder access to let the script proceed $Script:ControlledFolderAccess = $true Set-MpPreference -EnableControlledFolderAccess Disabled # Open "Ransomware protection" page Start-Process -FilePath windowsdefender://RansomwareProtection } "0" { $Script:ControlledFolderAccess = $false } } } #endregion Defender checks # Check for a pending reboot $PendingActions = @( # CBS pending "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending", "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootInProgress", "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\PackagesPending", # Windows Update pending "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\PostRebootReporting", "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" ) if (($PendingActions | Test-Path) -contains $true) { Write-Warning -Message $Localization.RebootPending Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } # Check whether the current module version is the latest one try { # Check the internet connection $Parameters = @{ Name = "dns.msftncsi.com" Server = "1.1.1.1" DnsOnly = $true ErrorAction = "Stop" } if ((Resolve-DnsName @Parameters).IPAddress -notcontains "131.107.255.255") { return } try { # https://github.com/farag2/Sophia-Script-for-Windows/blob/master/sophia_script_versions.json $Parameters = @{ Uri = "https://raw.githubusercontent.com/farag2/Sophia-Script-for-Windows/master/sophia_script_versions.json" Verbose = $true UseBasicParsing = $true } $LatestRelease = (Invoke-RestMethod @Parameters).Sophia_Script_Windows_10_LTSC2021 $CurrentRelease = (Get-Module -Name Sophia).Version.ToString() if ([System.Version]$LatestRelease -gt [System.Version]$CurrentRelease) { Write-Warning -Message $Localization.UnsupportedRelease Write-Verbose -Message "https://github.com/farag2/Sophia-Script-for-Windows/releases/latest" -Verbose Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } } catch [System.Net.WebException] { Write-Warning -Message ($Localization.NoResponse -f "https://github.com") Write-Error -Message ($Localization.NoResponse -f "https://github.com") -ErrorAction SilentlyContinue } } catch [System.ComponentModel.Win32Exception] { Write-Warning -Message $Localization.NoInternetConnection Write-Error -Message $Localization.NoInternetConnection -ErrorAction SilentlyContinue } # Check whether LGPO.exe exists in the bin folder if (-not (Test-Path -Path "$PSScriptRoot\..\bin\LGPO.exe")) { Write-Warning -Message $Localization.Bin Write-Verbose -Message "https://github.com/farag2/Sophia-Script-for-Windows/releases/latest" -Verbose Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } # Detect Windows build version if ((Get-WindowsEdition -Online).Edition -notmatch "EnterpriseS") { Write-Warning -Message $Localization.UnsupportedOSBuild Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose Write-Verbose -Message "https://github.com/farag2/Sophia-Script-for-Windows#system-requirements" -Verbose exit } switch ((Get-CimInstance -ClassName CIM_OperatingSystem).BuildNumber) { {$_ -ne 19044} { Write-Warning -Message $Localization.UnsupportedOSBuild Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose Write-Verbose -Message "https://github.com/farag2/Sophia-Script-for-Windows#system-requirements" -Verbose # Receive updates for other Microsoft products when you update Windows (New-Object -ComObject Microsoft.Update.ServiceManager).AddService2("7971f918-a847-4430-9279-4a52d1efe18d", 7, "") # Check for updates Start-Process -FilePath "$env:SystemRoot\System32\UsoClient.exe" -ArgumentList StartInteractiveScan # Open the "Windows Update" page Start-Process -FilePath "ms-settings:windowsupdate" exit } "19044" { # Check whether the current module version is the latest one try { # Check the internet connection $Parameters = @{ Name = "dns.msftncsi.com" Server = "1.1.1.1" DnsOnly = $true ErrorAction = "Stop" } if ((Resolve-DnsName @Parameters).IPAddress -notcontains "131.107.255.255") { return } try { # https://github.com/farag2/Sophia-Script-for-Windows/blob/master/supported_windows_builds.json $Parameters = @{ Uri = "https://raw.githubusercontent.com/farag2/Sophia-Script-for-Windows/master/supported_windows_builds.json" Verbose = $true UseBasicParsing = $true } $LatestSupportedBuild = (Invoke-RestMethod @Parameters).Windows_10_LTSC_2021 } catch [System.Net.WebException] { Write-Warning -Message ($Localization.NoResponse -f "https://github.com") Write-Error -Message ($Localization.NoResponse -f "https://github.com") -ErrorAction SilentlyContinue } } catch [System.ComponentModel.Win32Exception] { $LatestSupportedBuild = 0 Write-Warning -Message $Localization.NoInternetConnection Write-Error -Message $Localization.NoInternetConnection -ErrorAction SilentlyContinue } # We may use Test-Path -Path variable:LatestSupportedBuild if ((Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Windows nt\CurrentVersion" -Name UBR) -lt $LatestSupportedBuild) { # Check Windows minor build version # https://support.microsoft.com/en-us/topic/windows-10-update-history-857b8ccb-71e4-49e5-b3f6-7073197d98fb $CurrentBuild = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows nt\CurrentVersion" -Name CurrentBuild $UBR = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows nt\CurrentVersion" -Name UBR Write-Warning -Message ($Localization.UpdateWarning -f $CurrentBuild.CurrentBuild, $UBR.UBR, $LatestSupportedBuild) Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose Write-Verbose -Message "https://github.com/farag2/Sophia-Script-for-Windows#system-requirements" -Verbose # Receive updates for other Microsoft products when you update Windows (New-Object -ComObject Microsoft.Update.ServiceManager).AddService2("7971f918-a847-4430-9279-4a52d1efe18d", 7, "") # Check for updates Start-Process -FilePath "$env:SystemRoot\System32\UsoClient.exe" -ArgumentList StartInteractiveScan # Open the "Windows Update" page Start-Process -FilePath "ms-settings:windowsupdate" exit } } } # Enable back the SysMain service if it was disabled by harmful tweakers if ((Get-Service -Name SysMain).Status -eq "Stopped") { Get-Service -Name SysMain | Set-Service -StartupType Automatic Get-Service -Name SysMain | Start-Service Write-Verbose -Message "https://www.outsidethebox.ms/19318/" -Verbose } # Automatically manage paging file size for all drives if (-not (Get-CimInstance -ClassName CIM_ComputerSystem).AutomaticManagedPageFile) { Get-CimInstance -ClassName CIM_ComputerSystem | Set-CimInstance -Property @{AutomaticManagedPageFile = $true} } # Remove firewalled IP addresses that block Microsoft recourses added by harmful tweakers # https://wpd.app Get-NetFirewallRule | Where-Object -FilterScript {($_.DisplayName -match "Blocker MicrosoftTelemetry") -or ($_.DisplayName -match "Blocker MicrosoftExtra") -or ($_.DisplayName -match "windowsSpyBlocker")} | Remove-NetFirewallRule Write-Information -MessageData "" -InformationAction Continue # Extract the localized "Please wait..." string from shell32.dll Write-Verbose -Message ([WinAPI.GetStrings]::GetString(12612)) -Verbose Write-Information -MessageData "" -InformationAction Continue # Remove IP addresses from hosts file that block Microsoft recourses added by WindowsSpyBlocker # https://github.com/crazy-max/WindowsSpyBlocker try { # Check the internet connection $Parameters = @{ Name = "dns.msftncsi.com" Server = "1.1.1.1" DnsOnly = $true ErrorAction = "Stop" } if ((Resolve-DnsName @Parameters).IPAddress -notcontains "131.107.255.255") { return } try { # Check whether https://github.com is alive $Parameters = @{ Uri = "https://github.com" Method = "Head" DisableKeepAlive = $true UseBasicParsing = $true } if (-not (Invoke-WebRequest @Parameters).StatusDescription) { Write-Information -MessageData "" -InformationAction Continue Write-Verbose -Message $Localization.Skipped -Verbose return } Clear-Variable -Name IPArray -ErrorAction Ignore # https://github.com/crazy-max/WindowsSpyBlocker/tree/master/data/hosts $Parameters = @{ Uri = "https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/extra.txt" UseBasicParsing = $true Verbose = $true } $extra = (Invoke-WebRequest @Parameters).Content $Parameters = @{ Uri = "https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/extra_v6.txt" UseBasicParsing = $true Verbose = $true } $extra_v6 = (Invoke-WebRequest @Parameters).Content $Parameters = @{ Uri = "https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/spy.txt" UseBasicParsing = $true Verbose = $true } $spy = (Invoke-WebRequest @Parameters).Content $Parameters = @{ Uri = "https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/spy_v6.txt" UseBasicParsing = $true Verbose = $true } $spy_v6 = (Invoke-WebRequest @Parameters).Content $Parameters = @{ Uri = "https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/update.txt" UseBasicParsing = $true Verbose = $true } $update = (Invoke-WebRequest @Parameters).Content $Parameters = @{ Uri = "https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/update_v6.txt" UseBasicParsing = $true Verbose = $true } $update_v6 = (Invoke-WebRequest @Parameters).Content $IPArray += $extra, $extra_v6, $spy, $spy_v6, $update, $update_v6 # Split the Array variable content $IPArray = $IPArray -split "`r?`n" | Where-Object -FilterScript {$_ -notmatch "#"} Write-Information -MessageData "" -InformationAction Continue # Extract the localized "Please wait..." string from shell32.dll Write-Verbose -Message ([WinAPI.GetStrings]::GetString(12612)) -Verbose Write-Information -MessageData "" -InformationAction Continue # Check whether hosts contains any of string from $IPArray array if ((Get-Content -Path "$env:SystemRoot\System32\drivers\etc\hosts" -Encoding Default -Force | ForEach-Object -Process {$_.Trim()} | ForEach-Object -Process { ($_ -ne "") -and ($_ -ne " ") -and (-not $_.StartsWith("#")) -and ($IPArray -split "`r?`n" | Select-String -Pattern $_) }) -contains $true) { Write-Warning -Message ($Localization.TweakerWarning -f "WindowsSpyBlocker") # Clear hosts file $hosts = Get-Content -Path "$env:SystemRoot\System32\drivers\etc\hosts" -Encoding Default -Force $hosts | ForEach-Object -Process { if (($_ -ne "") -and (-not $_.StartsWith("#")) -and ($IPArray -split "`r?`n" | Select-String -Pattern $_.Trim())) { $hostsData = $_ $hosts = $hosts | Where-Object -FilterScript {$_ -notmatch $hostsData} } } $hosts | Set-Content -Path "$env:SystemRoot\System32\drivers\etc\hosts" -Encoding Default -Force Start-Process -FilePath notepad.exe "$env:SystemRoot\System32\drivers\etc\hosts" } } catch [System.Net.WebException] { Write-Warning -Message ($Localization.NoResponse -f "https://github.com") Write-Error -Message ($Localization.NoResponse -f "https://github.com") -ErrorAction SilentlyContinue Write-Error -Message ($Localization.RestartFunction -f $MyInvocation.Line.Trim()) -ErrorAction SilentlyContinue } } catch [System.ComponentModel.Win32Exception] { Write-Warning -Message $Localization.NoInternetConnection Write-Error -Message $Localization.NoInternetConnection -ErrorAction SilentlyContinue Write-Error -Message ($Localization.RestartFunction -f $MyInvocation.Line.Trim()) -ErrorAction SilentlyContinue } # PowerShell 5.1 (7.5 too) interprets 8.3 file name literally, if an environment variable contains a non-Latin word # https://github.com/PowerShell/PowerShell/issues/21070 Get-ChildItem -Path "$env:TEMP\Computer.txt", "$env:TEMP\User.txt" -Force -ErrorAction Ignore | Remove-Item -Recurse -Force -ErrorAction Ignore # Save all opened folders in order to restore them after File Explorer restart $Script:OpenedFolders = {(New-Object -ComObject Shell.Application).Windows() | ForEach-Object -Process {$_.Document.Folder.Self.Path}}.Invoke() <# .SYNOPSIS The "Show menu" function with the up/down arrow keys and enter key to make a selection .PARAMETER Menu Array of items to choose from .PARAMETER Default Default selected item in array .PARAMETER AddSkip Add localized extracted "Skip" string from shell32.dll .EXAMPLE Show-Menu -Menu $Items -Default 1 .LINK https://qna.habr.com/answer?answer_id=1522379 #> function script:Show-Menu { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [array] $Menu, [Parameter(Mandatory = $true)] [int] $Default, [Parameter(Mandatory = $false)] [switch] $AddSkip ) Write-Information -MessageData "" -InformationAction Continue # Add "Please use the arrow keys 🠕 and 🠗 on your keyboard to select your answer" to menu $Menu += $Localization.KeyboardArrows -f [System.Char]::ConvertFromUtf32(0x2191), [System.Char]::ConvertFromUtf32(0x2193) if ($AddSkip) { # Extract the localized "Skip" string from shell32.dll $Menu += [WinAPI.GetStrings]::GetString(16956) } # https://github.com/microsoft/terminal/issues/14992 [System.Console]::BufferHeight += $Menu.Count $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 (' {1} ' -f ($i+1), $item) -InformationAction Continue } else { Write-Information -MessageData ('[ {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)) } # Extract the localized "Browse" string from shell32.dll $Script:Browse = [WinAPI.GetStrings]::GetString(9015) # Extract the localized "&No" string from shell32.dll $Script:No = [WinAPI.GetStrings]::GetString(33232).Replace("&", "") # Extract the localized "&Yes" string from shell32.dll $Script:Yes = [WinAPI.GetStrings]::GetString(33224).Replace("&", "") $Script:KeyboardArrows = $Localization.KeyboardArrows -f [System.Char]::ConvertFromUtf32(0x2191), [System.Char]::ConvertFromUtf32(0x2193) # Extract the localized "Skip" string from shell32.dll $Script:Skip = [WinAPI.GetStrings]::GetString(16956) # Display a warning message about whether a user has customized the preset file if ($Warning) { # Get the name of a preset (e.g Sophia.ps1) regardless it was named # $_.File has no EndsWith() method $PresetName = Split-Path -Path (((Get-PSCallStack).Position | Where-Object -FilterScript {$_.File}).File | Where-Object -FilterScript {$_.EndsWith(".ps1")}) -Leaf Write-Verbose -Message ($Localization.CustomizationWarning -f $PresetName) -Verbose do { $Choice = Show-Menu -Menu @($Yes, $No) -Default 2 switch ($Choice) { $Yes { continue } $No { Invoke-Item -Path $PSScriptRoot\..\$PresetName Start-Sleep -Seconds 5 Write-Verbose -Message "https://github.com/farag2/Sophia-Script-for-Windows#how-to-use" -Verbose Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } $KeyboardArrows {} } } until ($Choice -ne $KeyboardArrows) } } #endregion InitialActions #region Protection # Enable script logging. The log will be being recorded into the script root folder # To stop logging just close the console or type "Stop-Transcript" function Logging { $TranscriptFilename = "Log-$((Get-Date).ToString("dd.MM.yyyy-HH-mm"))" Start-Transcript -Path $PSScriptRoot\..\$TranscriptFilename.txt -Force } # Create a restore point for the system drive function CreateRestorePoint { $SystemDriveUniqueID = (Get-Volume | Where-Object -FilterScript {$_.DriveLetter -eq "$($env:SystemDrive[0])"}).UniqueID $SystemProtection = ((Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SPP\Clients" -ErrorAction Ignore)."{09F7EDC5-294E-4180-AF6A-FB0E6A0E9513}") | Where-Object -FilterScript {$_ -match [regex]::Escape($SystemDriveUniqueID)} $Script:ComputerRestorePoint = $false if ($null -eq $SystemProtection) { $ComputerRestorePoint = $true Enable-ComputerRestore -Drive $env:SystemDrive } # Never skip creating a restore point New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -Name SystemRestorePointCreationFrequency -PropertyType DWord -Value 0 -Force Checkpoint-Computer -Description "Sophia Script for Windows 10" -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 # Turn off System Protection for the system drive if it was turned off before without deleting the existing restore points if ($Script:ComputerRestorePoint) { Disable-ComputerRestore -Drive $env:SystemDrive } } #endregion Protection #region Additional function <# .SYNOPSIS Create pre-configured text files for LGPO.exe tool .EXAMPLE Set-Policy -Scope Computer -Path SOFTWARE\Policies\Microsoft\Windows\DataCollection -Name AllowTelemetry -Type DWORD -Value 0 .NOTES https://techcommunity.microsoft.com/t5/microsoft-security-baselines/lgpo-exe-local-group-policy-object-utility-v1-0/ba-p/701045 .NOTES Machine-wide user #> function script:Set-Policy { [CmdletBinding()] param ( [Parameter( Mandatory = $true, Position = 1 )] [string] [ValidateSet("Computer", "User")] $Scope, [Parameter( Mandatory = $true, Position = 2 )] [string] $Path, [Parameter( Mandatory = $true, Position = 3 )] [string] $Name, [Parameter( Mandatory = $true, Position = 4 )] [ValidateSet("DWORD", "SZ", "EXSZ", "CLEAR")] [string] $Type, [Parameter( Mandatory = $false, Position = 5 )] $Value ) if (-not (Test-Path -Path "$env:SystemRoot\System32\gpedit.msc")) { Write-Information -MessageData "" -InformationAction Continue Write-Verbose -Message $Localization.Skipped -Verbose return } switch ($Type) { "CLEAR" { $Policy = @" $Scope $($Path) $($Name) $($Type)`n "@ } default { $Policy = @" $Scope $($Path) $($Name) $($Type):$($Value)`n "@ } } if ($Scope -eq "Computer") { $Path = "$env:TEMP\Computer.txt" } else { $Path = "$env:TEMP\User.txt" } Add-Content -Path $Path -Value $Policy -Encoding Default -Force } #endregion Additional function #region Privacy & Telemetry <# .SYNOPSIS The Connected User Experiences and Telemetry (DiagTrack) service .PARAMETER Disable Disable the Connected User Experiences and Telemetry (DiagTrack) service, and block connection for the Unified Telemetry Client Outbound Traffic .PARAMETER Enable Enable the Connected User Experiences and Telemetry (DiagTrack) service, and allow connection for the Unified Telemetry Client Outbound Traffic .EXAMPLE DiagTrackService -Disable .EXAMPLE DiagTrackService -Enable .NOTES Current user #> function DiagTrackService { param ( [Parameter( Mandatory = $true, ParameterSetName = "Disable" )] [switch] $Disable, [Parameter( Mandatory = $true, ParameterSetName = "Enable" )] [switch] $Enable ) # Check whether "InitialActions" function was removed in preset file if (-not ("WinAPI.GetStrings" -as [type])) { # Get the name of a preset (e.g Sophia.ps1) regardless it was named # $_.File has no EndsWith() method $PresetName = Split-Path -Path (((Get-PSCallStack).Position | Where-Object -FilterScript {$_.File}).File | Where-Object -FilterScript {$_.EndsWith(".ps1")}) -Leaf Write-Information -MessageData "" -InformationAction Continue Write-Verbose -Message ($Localization.InitialActionsCheckFailed -f $PresetName) -Verbose Write-Verbose -Message "https://t.me/sophia_chat" -Verbose Write-Verbose -Message "https://discord.gg/sSryhaEv79" -Verbose exit } switch ($PSCmdlet.ParameterSetName) { "Disable" { # Connected User Experiences and Telemetry Get-Service -Name DiagTrack | Stop-Service -Force Get-Service -Name DiagTrack | Set-Service -StartupType Disabled # Block connection for the Unified Telemetry Client Outbound Traffic Get-NetFirewallRule -Group DiagTrack | Set-NetFirewallRule -Enabled True -Action Block } "Enable" { # Connected User Experiences and Telemetry Get-Service -Name DiagTrack | Set-Service -StartupType Automatic Get-Service -Name DiagTrack | Start-Service # Allow connection for the Unified Telemetry Client Outbound Traffic Get-NetFirewallRule -Group DiagTrack | Set-NetFirewallRule -Enabled True -Action Allow } } } <# .SYNOPSIS Diagnostic data .PARAMETER Minimal Set the diagnostic data collection to minimum .PARAMETER Default Set the diagnostic data collection to default .EXAMPLE DiagnosticDataLevel -Minimal .EXAMPLE DiagnosticDataLevel -Default .NOTES Machine-wide #> function DiagnosticDataLevel { param ( [Parameter( Mandatory = $true, ParameterSetName = "Minimal" )] [switch] $Minimal, [Parameter( Mandatory = $true, ParameterSetName = "Default" )] [switch] $Default ) if (-not (Test-Path -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection)) { New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection -Force } if (-not (Test-Path -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack)) { New-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack -Force } switch ($PSCmdlet.ParameterSetName) { "Minimal" { # Security level New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection -Name AllowTelemetry -PropertyType DWord -Value 0 -Force New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name MaxTelemetryAllowed -PropertyType DWord -Value 1 -Force New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack -Name ShowedToastAtLevel -PropertyType DWord -Value 1 -Force Set-Policy -Scope Computer -Path SOFTWARE\Policies\Microsoft\Windows\DataCollection -Name AllowTelemetry -Type DWORD -Value 0 } "Default" { # Optional diagnostic data New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection -Name MaxTelemetryAllowed -PropertyType DWord -Value 3 -Force New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack -Name ShowedToastAtLevel -PropertyType DWord -Value 3 -Force Remove-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection -Name AllowTelemetry -Force -ErrorAction Ignore Set-Policy -Scope Computer -Path SOFTWARE\Policies\Microsoft\Windows\DataCollection -Name AllowTelemetry -Type CLEAR } } } <# .SYNOPSIS Windows Error Reporting .PARAMETER Disable Turn off Windows Error Reporting .PARAMETER Enable Turn on Windows Error Reporting .EXAMPLE ErrorReporting -Disable .EXAMPLE ErrorReporting -Enable .NOTES Current user #> function ErrorReporting { param ( [Parameter( Mandatory = $true, ParameterSetName = "Disable" )] [switch] $Disable, [Parameter( Mandatory = $true, ParameterSetName = "Enable" )] [switch] $Enable ) switch ($PSCmdlet.ParameterSetName) { "Disable" { if ((Get-WindowsEdition -Online).Edition -notmatch "Core") { Get-ScheduledTask -TaskName QueueReporting | Disable-ScheduledTask New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Windows Error Reporting" -Name Disabled -PropertyType DWord -Value 1 -Force } Get-Service -Name WerSvc | Stop-Service -Force Get-Service -Name WerSvc | Set-Service -StartupType Disabled } "Enable" { Get-ScheduledTask -TaskName QueueReporting | Enable-ScheduledTask Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Windows Error Reporting" -Name Disabled -Force -ErrorAction Ignore Get-Service -Name WerSvc | Set-Service -StartupType Manual Get-Service -Name WerSvc | Start-Service } } } <# .SYNOPSIS The feedback frequency .PARAMETER Never Change the feedback frequency to "Never" .PARAMETER Automatically Change feedback frequency to "Automatically" .EXAMPLE FeedbackFrequency -Never .EXAMPLE FeedbackFrequency -Automatically .NOTES Current user #> function FeedbackFrequency { param ( [Parameter( Mandatory = $true, ParameterSetName = "Never" )] [switch] $Never, [Parameter( Mandatory = $true, ParameterSetName = "Automatically" )] [switch] $Automatically ) switch ($PSCmdlet.ParameterSetName) { "Never" { 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 } "Automatically" { Remove-Item -Path HKCU:\Software\Microsoft\Siuf\Rules -Force -ErrorAction Ignore } } } <# .SYNOPSIS The diagnostics tracking scheduled tasks .PARAMETER Disable Turn off the diagnostics tracking scheduled tasks .PARAMETER Enable Turn on the diagnostics tracking scheduled tasks .EXAMPLE ScheduledTasks -Disable .EXAMPLE ScheduledTasks -Enable .NOTES A pop-up dialog box lets a user select tasks .NOTES Current user #> function ScheduledTasks { param ( [Parameter( Mandatory = $true, ParameterSetName = "Disable" )] [switch] $Disable, [Parameter( Mandatory = $true, ParameterSetName = "Enable" )] [switch] $Enable ) Add-Type -AssemblyName PresentationCore, PresentationFramework #region Variables # Initialize an array list to store the selected scheduled tasks $SelectedTasks = New-Object -TypeName System.Collections.ArrayList($null) # The following tasks will have their checkboxes checked [string[]]$CheckedScheduledTasks = @( # 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", # 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" ) #endregion Variables #region XAML Markup # The section defines the design of the upcoming dialog box [xml]$XAML = @"