From fc95cdea41f7db08316abc75980e317ef22c7e74 Mon Sep 17 00:00:00 2001 From: Dmitry Nefedov Date: Thu, 21 Jan 2021 13:57:50 +0300 Subject: [PATCH] 20.01.2020 v5.3.3 --- Sophia/PowerShell 7.x/Sophia.ps1 | 46 +++++-- Sophia/PowerShell 7.x/Sophia.psd1 | Bin 0 -> 1772 bytes Sophia/PowerShell 7.x/Sophia.psm1 | 208 ++++++++++++++++++++---------- 3 files changed, 178 insertions(+), 76 deletions(-) create mode 100644 Sophia/PowerShell 7.x/Sophia.psd1 diff --git a/Sophia/PowerShell 7.x/Sophia.ps1 b/Sophia/PowerShell 7.x/Sophia.ps1 index 6d94d343..c7003235 100644 --- a/Sophia/PowerShell 7.x/Sophia.ps1 +++ b/Sophia/PowerShell 7.x/Sophia.ps1 @@ -2,14 +2,14 @@ .SYNOPSIS Default preset file for "Windows 10 Sophia Script" - Version: v5.3.2 - Date: 15.01.2021 + Version: v5.3.3 + Date: 20.01.2021 Copyright (c) 2021 farag & oZ-Zo Thanks to all https://forum.ru-board.com members involved .DESCRIPTION - Supported Windows 10 versions: 2004 (20H1)/2009 (20H2), 19041/19042, Home/Pro/Enterprise, x64 + Supported Windows 10 versions: 2004 (20H1)/20H2 (2009), 19041/19042, Home/Pro/Enterprise, x64 Due to the fact that the script includes more than 150 functions with different arguments, you must read the entire Sophia.ps1 carefully and comment out/uncomment those functions that you do/do not want to be executed @@ -37,15 +37,40 @@ #Requires -RunAsAdministrator #Requires -Version 7.1 +[CmdletBinding()] +param +( + [Parameter(Mandatory = $false)] + [string[]] + $Functions +) + Clear-Host -$Host.UI.RawUI.WindowTitle = "Windows 10 Sophia Script v5.3.2 | ©️ farag & oz-zo, 2015–2021" +$Host.UI.RawUI.WindowTitle = "Windows 10 Sophia Script v5.3.3 | ©️ farag & oz-zo, 2015–2021" Remove-Module -Name Sophia -Force -ErrorAction Ignore Import-Module -Name $PSScriptRoot\Sophia.psd1 -PassThru -Force Import-LocalizedData -BindingVariable Global:Localization -FileName Sophia +<# + .SYNOPSIS + Adds the feature to run the script by specifying module functions as parameters + Добавляет возможность запускать скрипт, указывая в качестве параметров функции модуля + + .EXAMPLE + .\Sophia.ps1 -Functions "FunctionName1 -Parameter", "FunctionName2 -Parameter" +#> +if ($Functions) +{ + foreach ($Function in $Functions) + { + Invoke-Expression -Command $Function + } + exit +} + # Checkings # Проверки Checkings @@ -610,8 +635,8 @@ UpdateMicrosoftProducts -Enable # Не подключаться к службе Microsoft Update так, чтобы при обновлении Windows не получать обновления для других продуктов Майкрософт (значение по умолчанию) # UpdateMicrosoftProducts -Disable -# Do not let all UWP apps run in the background (current user only) -# Не разрешать всем UWP-приложениям работать в фоновом режиме (только для текущего пользователя) +# Do not let UWP apps run in the background (current user only) +# Не разрешать UWP-приложениям работать в фоновом режиме (только для текущего пользователя) BackgroundUWPApps -Disable # Let all UWP apps run in the background (current user only) (default value) @@ -1065,8 +1090,13 @@ PUAppsDetection -Enable # Выключить обнаружение потенциально нежелательных приложений и блокировать их (значение по умолчанию) # PUAppsDetection -Disable -# Enable sandboxing for Microsoft Defender -# Включить песочницу для Microsoft Defender +<# + Enable sandboxing for Microsoft Defender + There is a bug in KVM with QEMU: enabling this function causes VM to freeze up during the loading phase of Windows + + Включить песочницу для Microsoft Defender + В KVM с QEMU присутсвует баг: включение этой функции приводит ВМ к зависанию во время загрузки Windows +#> DefenderSandbox -Enable # Disable sandboxing for Microsoft Defender (default value) diff --git a/Sophia/PowerShell 7.x/Sophia.psd1 b/Sophia/PowerShell 7.x/Sophia.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..4f5bfa25024590429da23c0c84f1a57214aaeff8 GIT binary patch literal 1772 zcmc(gTW=Ck6ovOICO-KGCO&ve3KT)q#6(hRC8S zcr$5EX3k~yW$m^1KJ(}IYx`+;?T(e~%%+UFz2iNwg-tB6XwP`X`9u4Fyq8Dde2i2L+=n2)7im>v9R(gEd%%8b z=R|tWTxQoIvlHfxuiWht@}n$WIdtVUwl@15Z<4?l~WQG;@X`Y4P;2r5q=$gnP!Sh`vP!wW+E48p9hGnIt`TxqZaa zvHgHgSq!u7F+5r6`c4vtl)Q+61lyY9mA_5@maIpN`@fd#6f24(Ba(#9lGUQJykAw` z+;#Fxt1w1Li0cKNQASsJs08&@W4E1G^_zMvyc@LJ)K3Ll6D(bztE}dDP<|@l>(~*z zbdf(^vsdD7@>%$boLIaq@8i`wG*o3)ZR0fiEI$W@N4xC I^0R;c1*5M98vp function ScheduledTasks { @@ -3415,7 +3428,8 @@ function InstallOneDrive return } } - Get-ScheduledTask -TaskName "Onedrive* Update*" | Start-ScheduledTask + + Get-ScheduledTask -TaskName "Onedrive* Update*" | Enable-ScheduledTask } } #endregion OneDrive @@ -3825,7 +3839,7 @@ function TempFolder } "1" { - Write-Verbose -Message $Localization.SkippedSymbolic -Verbose + Write-Verbose -Message $Localization.SymbolicSkipped -Verbose } } } @@ -4578,11 +4592,13 @@ function WindowsFeatures WindowsCapabilities -Enable .NOTES - A pop-up dialog box enables the user to select features to remove + A pop-up dialog box enables the user to select features Current user only - Используется всплывающее диалоговое окно, позволяющее пользователю отметить компоненты на удаление + Используется всплывающее диалоговое окно, позволяющее пользователю отмечать компоненты Только для текущего пользователя + + Made by https://github.com/oz-zo #> function WindowsCapabilities { @@ -4621,15 +4637,6 @@ function WindowsCapabilities # Быстрая поддержка (Майкрософт) "App.Support.QuickAssist*", - <# - Windows Media Player - Проигрыватель Windows Media - - If you want to leave "Multimedia settings" in the advanced settings of Power Options do not uninstall this feature - Если вы хотите оставить параметр "Параметры мультимедиа" в дополнительных параметрах электропитания, не удаляйте этот компонент - #> - "Media.WindowsMediaPlayer*", - # Microsoft Paint "Microsoft.Windows.MSPaint*", @@ -4641,16 +4648,40 @@ function WindowsCapabilities "Print.Fax.Scan*" ) + # The following FODv2 items will have their checkboxes unchecked + # Следующие дополнительные компоненты будут иметь чекбоксы неотмеченными + $UncheckedCapabilities = @( + # Internet Explorer 11 + "Browser.InternetExplorer*", + + # Math Recognizer + # Распознаватель математических знаков + "MathRecognizer*", + + <# + Windows Media Player + Проигрыватель Windows Media + + If you want to leave "Multimedia settings" element in the advanced settings of Power Options do not uninstall this feature + Если вы хотите оставить параметр "Параметры мультимедиа" в дополнительных параметрах электропитания, не удаляйте этот компонент + #> + "Media.WindowsMediaPlayer*", + + # Language components + # Языковые компоненты + "OpenSSH.Client*" + ) + # The following FODv2 items will be excluded from the display # Следующие дополнительные компоненты будут исключены из отображения $ExcludedCapabilities = @( # The DirectX Database to configure and optimize apps when multiple Graphics Adapters are present # База данных DirectX для настройки и оптимизации приложений при наличии нескольких графических адаптеров - "DirectX\.Configuration\.Database", + "DirectX.Configuration.Database*", # Language components # Языковые компоненты - "Language\.", + "Language.*", # Notepad # Блокнот @@ -4658,15 +4689,19 @@ function WindowsCapabilities # Mail, contacts, and calendar sync component # Компонент синхронизации почты, контактов и календаря - "OneCoreUAP\.OneSync", + "OneCoreUAP.OneSync*", + + # Windows PowerShell Intergrated Scripting Enviroment + # Интегрированная среда сценариев Windows PowerShell + "Microsoft.Windows.PowerShell.ISE*", # Management of printers, printer drivers, and printer servers # Управление принтерами, драйверами принтеров и принт-серверами - "Print\.Management\.Console", + "Print.Management.Console*", # Features critical to Windows functionality # Компоненты, критичные для работоспособности Windows - "Windows\.Client\.ShellComponents" + "Windows.Client.ShellComponents*" ) #endregion Variables @@ -4759,6 +4794,11 @@ function WindowsCapabilities $OFS = "|" Get-WindowsCapability -Online | Where-Object -FilterScript {$_.Name -cmatch $Capabilities} | Remove-WindowsCapability -Online $OFS = " " + + if (([string]$Capabilities -cmatch "Print.Fax.Scan*") -or ([string]$Capabilities -cmatch "Browser.InternetExplorer*")) + { + Write-Warning -Message $Localization.RestartWarning + } } function EnableButton @@ -4769,6 +4809,11 @@ function WindowsCapabilities $OFS = "|" Get-WindowsCapability -Online | Where-Object -FilterScript {$_.Name -cmatch $Capabilities} | Add-WindowsCapability -Online $OFS = " " + + if (([string]$Capabilities -cmatch "Print.Fax.Scan*") -or ([string]$Capabilities -cmatch "Browser.InternetExplorer*")) + { + Write-Warning -Message $Localization.RestartWarning + } } function Add-CapabilityControl @@ -4797,15 +4842,19 @@ function WindowsCapabilities [void]$PanelContainer.Children.Add($StackPanel) - $CheckBox.IsChecked = $false - # If capability checked, add to the array list to remove # Если компонент выделен, то добавить в массив для удаления - if ($CheckedCapabilities | Where-Object -FilterScript {$Capability -like $_}) + if ($UnCheckedCapabilities | Where-Object -FilterScript {$Capability -like $_}) { - $CheckBox.IsChecked = $true - [void]$Capabilities.Add($Capability) + $CheckBox.IsChecked = $false + # Exit function, item is not checked + # Выход из функции, если элемент не выделен + return } + + # If capability checked, add to the array list to remove + # Если компонент выделен, то добавить в массив для удаления + [void]$Capabilities.Add($Capability) } #endregion Functions @@ -4813,12 +4862,23 @@ function WindowsCapabilities { "Enable" { + try + { + (Invoke-WebRequest -Uri https://www.google.com -UseBasicParsing -DisableKeepAlive -Method Head).StatusDescription + } + catch [System.Net.WebException] + { + Write-Warning -Message $Localization.NoInternetConnection + Write-Error -Message $Localization.NoInternetConnection -ErrorAction SilentlyContinue + return + } + #region Events Handlers $OptionalCapabilities = New-Object -TypeName System.Collections.ArrayList($null) # Window Loaded Event $Window.Add_Loaded({ $OFS = "|" - $OptionalCapabilities = Get-WindowsCapability -Online | Where-Object -FilterScript {($_.State -eq "NotPresent") -and ($_.Name -cmatch $CheckedCapabilities) -and ($_.Name -cnotmatch $ExcludedCapabilities)} + $OptionalCapabilities = Get-WindowsCapability -Online | Where-Object -FilterScript {($_.State -eq "NotPresent") -and ($_.Name -cmatch $CheckedCapabilities) -($_.Name -cmatch $UncheckedCapabilities) -and ($_.Name -cnotmatch $ExcludedCapabilities)} if ($OptionalCapabilities.Count -gt 0) { $OptionalCapabilities | ForEach-Object -Process { @@ -4846,7 +4906,7 @@ function WindowsCapabilities # Window Loaded Event $Window.Add_Loaded({ $OFS = "|" - $OptionalCapabilities = Get-WindowsCapability -Online | Where-Object -FilterScript {($_.State -eq "Installed") -and ($_.Name -cmatch $CheckedCapabilities) -and ($_.Name -cnotmatch $ExcludedCapabilities)} + $OptionalCapabilities = Get-WindowsCapability -Online | Where-Object -FilterScript {($_.State -eq "Installed") -and ($_.Name -cnotmatch $ExcludedCapabilities)} if ($OptionalCapabilities.Count -gt 0) { $OptionalCapabilities | ForEach-Object -Process { @@ -4869,17 +4929,6 @@ function WindowsCapabilities } } - try - { - (Invoke-WebRequest -Uri https://www.google.com -UseBasicParsing -DisableKeepAlive -Method Head).StatusDescription - } - catch [System.Net.WebException] - { - Write-Warning -Message $Localization.NoInternetConnection - Write-Error -Message $Localization.NoInternetConnection -ErrorAction SilentlyContinue - return - } - Write-Verbose -Message $Localization.DialogBoxOpening -Verbose $Window.Title = $Localization.FODWindowTitle @@ -4946,16 +4995,16 @@ function UpdateMicrosoftProducts <# .SYNOPSIS - Do not let/let UWP apps run in the background, except the followings... - Не разрешать/разрешать UWP-приложениям работать в фоновом режиме, кроме следующих... + Do not let/let UWP apps run in the background + Не разрешать/разрешать UWP-приложениям работать в фоновом режиме .PARAMETER Disable - Do not let UWP apps run in the background, except the followings... - Не разрешать UWP-приложениям работать в фоновом режиме, кроме следующих... + Do not let UWP apps run in the background, except those are saved in $ExcludedBackgroundApps variable + Не разрешать UWP-приложениям работать в фоновом режиме, кроме тех, что сохранены в переменной $ExcludedBackgroundApps .PARAMETER Enable - Let UWP apps run in the background, except the followings... - Разрешать UWP-приложениям работать в фоновом режиме, кроме следующих... + Let all UWP apps run in the background + Разрешать всем UWP-приложениям работать в фоновом режиме .EXAMPLE BackgroundUWPApps -Disable @@ -5329,13 +5378,10 @@ function SetUserShellFolderLocation $Default ) - function UserShellFolder - { <# .SYNOPSIS Change the location of the each user folder using SHSetKnownFolderPath function Изменить расположение каждой пользовательской папки, используя функцию "SHSetKnownFolderPath" - https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath .PARAMETER RemoveDesktopINI The RemoveDesktopINI argument removes desktop.ini in the old user shell folder @@ -5347,7 +5393,11 @@ function SetUserShellFolderLocation .NOTES User files or folders won't me moved to a new location Пользовательские файлы не будут перенесены в новое расположение + + https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath #> + function UserShellFolder + { [CmdletBinding()] param ( @@ -5513,8 +5563,10 @@ public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, Int ShowMenu -Menu $ListOfItems -Default $DefaultChoice .NOTES - Не работает в PowerShell ISE Doesn't work in PowerShell ISE + Не работает в PowerShell ISE + + https://qna.habr.com/user/MaxKozlov #> function ShowMenu { @@ -5595,11 +5647,11 @@ public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, Int # Если количество дисков больше одного, сделать второй диск в списке диском по умолчанию if ($DriveLetters.Count -gt 1) { - $Global:Default = 1 + $Script:Default = 1 } else { - $Global:Default = 0 + $Script:Default = 0 } # Desktop @@ -5619,7 +5671,7 @@ public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, Int { "0" { - $SelectedDrive = ShowMenu -Title $Localization.DesktopDriveSelect -Menu $DriveLetters -Default $Global:Default + $SelectedDrive = ShowMenu -Title $Localization.DesktopDriveSelect -Menu $DriveLetters -Default $Script:Default UserShellFolder -UserFolder Desktop -FolderPath "${SelectedDrive}:\Desktop" -RemoveDesktopINI } "1" @@ -5645,7 +5697,7 @@ public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, Int { "0" { - $SelectedDrive = ShowMenu -Title $Localization.DocumentsDriveSelect -Menu $DriveLetters -Default $Global:Default + $SelectedDrive = ShowMenu -Title $Localization.DocumentsDriveSelect -Menu $DriveLetters -Default $Script:Default UserShellFolder -UserFolder Documents -FolderPath "${SelectedDrive}:\Documents" -RemoveDesktopINI } "1" @@ -5671,7 +5723,7 @@ public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, Int { "0" { - $SelectedDrive = ShowMenu -Title $Localization.DownloadsDriveSelect -Menu $DriveLetters -Default $Global:Default + $SelectedDrive = ShowMenu -Title $Localization.DownloadsDriveSelect -Menu $DriveLetters -Default $Script:Default UserShellFolder -UserFolder Downloads -FolderPath "${SelectedDrive}:\Downloads" -RemoveDesktopINI } "1" @@ -5697,7 +5749,7 @@ public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, Int { "0" { - $SelectedDrive = ShowMenu -Title $Localization.MusicDriveSelect -Menu $DriveLetters -Default $Global:Default + $SelectedDrive = ShowMenu -Title $Localization.MusicDriveSelect -Menu $DriveLetters -Default $Script:Default UserShellFolder -UserFolder Music -FolderPath "${SelectedDrive}:\Music" -RemoveDesktopINI } "1" @@ -5723,7 +5775,7 @@ public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, Int { "0" { - $SelectedDrive = ShowMenu -Title $Localization.PicturesDriveSelect -Menu $DriveLetters -Default $Global:Default + $SelectedDrive = ShowMenu -Title $Localization.PicturesDriveSelect -Menu $DriveLetters -Default $Script:Default UserShellFolder -UserFolder Pictures -FolderPath "${SelectedDrive}:\Pictures" -RemoveDesktopINI } "1" @@ -5749,7 +5801,7 @@ public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, Int { "0" { - $SelectedDrive = ShowMenu -Title $Localization.VideosDriveSelect -Menu $DriveLetters -Default $Global:Default + $SelectedDrive = ShowMenu -Title $Localization.VideosDriveSelect -Menu $DriveLetters -Default $Script:Default UserShellFolder -UserFolder Videos -FolderPath "${SelectedDrive}:\Videos" -RemoveDesktopINI } "1" @@ -7424,7 +7476,7 @@ function syspin } Invoke-WebRequest @Parameters - $Global:syspin = $true + $Script:syspin = $true } } catch [System.Net.WebException] @@ -7555,18 +7607,27 @@ function PinCommandPrompt #region UWP apps <# .SYNOPSIS - Uninstall UWP apps using the pop-up dialog box that enables the user to select packages to remove - App packages will not be installed for new users if the "Uninstall for All Users" box is checked + Uninstall UWP apps + Удалить UWP-приложения - Удалить UWP-приложения, используя всплывающее диалоговое окно, позволяющее пользователю отметить пакеты на удаление - Приложения не будут установлены для новых пользователе, если отмечено "Удалять для всех пользователей" - - .NOTES + .DESCRIPTION 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 Добавьте имена пакетов UWP-приложений в массив $UncheckedAppXPackages, получив названия их пакетов с помощью команды: (Get-AppxPackage -PackageTypeFilter Bundle -AllUsers).Name + + App packages will not be installed for new users if the "Uninstall for All Users" box is checked + Приложения не будут установлены для новых пользователе, если отмечено "Удалять для всех пользователей" + + .NOTES + A pop-up dialog box enables the user to select packages + Используется всплывающее диалоговое окно, позволяющее пользователю отмечать пакеты + + Current user only + Только для текущего пользователя + + Made by https://github.com/oz-zo #> function UninstallUWPApps { @@ -8850,6 +8911,10 @@ function PUAppsDetection .EXAMPLE DefenderSandbox -Enable + + .NOTES + There is a bug in KVM with QEMU: enabling this function causes VM to freeze up during the loading phase of Windows + В KVM с QEMU присутсвует баг: включение этой функции приводит ВМ к зависанию во время загрузки Windows #> function DefenderSandbox { @@ -10621,6 +10686,13 @@ public static void PostMessage() # Перезапустить меню "Пуск" Stop-Process -Name StartMenuExperienceHost -Force -ErrorAction Ignore + # Turn on Controlled folder access if it was turned on + # Включить контролируемый доступ к папкам, если был включен + if ($Script:ControlledFolderAccess) + { + Set-MpPreference -EnableControlledFolderAccess Enabled + } + Write-Warning -Message $Localization.RestartWarning } #endregion Refresh