﻿
 :: 2020 westlife, LeX333666 (LeX_6000), forum: http://forum.ru-board.com/topic.cgi?forum=62&bm=1&topic=30617&glp

 :: WARNING: English versions of presets: "Presets_EN.txt" and "QuickPresets_EN.txt" can be used instead of the originals: "Presets.txt" and "QuickPresets.txt"
 :: Move the presets files from "\AutoSettingsPS\Files\EN\..." to the root folder: "\AutoSettingsPS\..."

 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 :: Permalinks to all scripts:                                                       ::
 ::  Yandex Disk: https://yadi.sk/d/CMqvcp1F3QiaWL                                   ::
 :: Google Drive: https://drive.google.com/open?id=1lxbiaL5-EF65EVpbogqInfXmYk-oJd2H ::
 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 :: You can support me financially through these payment systems:                    ::
 :: Sberbank Maestro: 6390 0204 9003 8140 27 (18 цифр, Алексей Т.)                   ::
 :: Ренессанс Кредит: 5161 1612 0941 6142                                            ::
 :: Yandex Money: https://yoomoney.ru/to/410018438535989                             ::
 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

 :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 ::                                                                 ::
 ::    IMPORTANT!!!     READ ALL INFORMATION !!!                    ::
 ::                                                                 ::
 :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

 AutoSettingsPS - it’s a tool for automatically settings basic Windows parameters,
 perform updates from a folder or Maintenance, with the ability to configure the script for yourself, open source,
 and display of all actions, with a description. Made for personal use and laid out for everyone.
 Written in PowerShell 5.

 In all descriptions, only the most important, since everything is not possible to describe, and not to remember everything.
 This is a completely new project, made from scratch, in PowerShell, with other algorithms, implementations
 and additional features than it was in the previous AutoSettings.bat, but with similar management and design.

 To use, you do not need to know PowerShell or install anything.
 AutoSettingsPS is fully autonomous, and works from a folder.
 Changes to Windows are made only by the user’s choice in the menu,
 and it is possible to restore all the script parameters back to default.

 All settings adapted for Windows 10 x64/x86 1809 (17763) and higher.

 The main objective of AutoSettingsPS - is to free Windows resources from unnecessary continuous actions.
 Disable all possible data collection, and modern functions, leaving the standard Windows functionality for games or work.
 With the ability to add your own tweaks to it, and configure it for yourself.


    ╔═════╗
 ■══╝  1  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Description of the general structure of all menus of the AutoSettingsPS settings complex
   All configurable settings can be restored to default, as in untouched Windows

 The Main Menu is divided into groups:

 [0] = Quick Settings | Quick settings for almost all menus at once

       It used to automate the configuration of almost all AutoSettingsPS parameters in one pass
       From most separate menus and separate scripts. The number of applied parameters is configured by the preset: \QuickPresets.txt
       QuickPresets.txt is configured for the optimal configuration option, each one can customize it individually.
       The specified parameters in \QuickPresets.txt, in turn, are guided by the main preset: \Presets.txt

 [1] = Configs-Checks | Applying and Validating Some Important Windows Settings

       Used to track and re-apply some groups of parameters, from several menus and scripts


 Next comes the entire set of separate menus for manual sequential configuration and maintenance of Windows.
 All menus include groups of settings that are interconnected or relate to the same direction.


 [2] = SelfMenu | A group of different menus for personal settings Windows

       Used to configure some important Windows settings to your preferences, as everyone has their own.

        [1] = Defender | Configuring Windows Defender
        [2] = Boot optimization | Configure Hibernation, Fast Boot, Boot Optimization
        [3] = Search, Cortana, Indexing | Settings related to the search

        [4] = Network | A group of settings related to the network, it also includes a separate menu for setting up a local network.
        [5] = Explorer | Explorer-related settings: display folders, icons, wallpapers, set drive icons, clear the thumbnail cache and icons.

        [6] = Windows Photo Viewer | Restores the parameters of the standard viewer
        [7] = Event logs | Enables or disables event logs and lists active logs.
        [8] = User Account Control | Configures some UAC modes
        [9] = Registry Backup Task | Creating Your Own Task MyRegIdleBackup. In general, there is an opportunity to make the standard task work.

       [10] = User Folders | Menu to change the location (My Documents, Music etc.)
       [11] = Temp Folder: User   | Change location for temp folder
       [12] = Temp Folder: System | Changing the location for the system temp folder
       [13] = Prevent launch exe files | Blocking the launch of Exe files by name, if you want to prohibit the execution of something on the system, apply carefully.

       [14] = Manage Apps/Appx | Download/Install/Re-registration/Uninstall Modern Applications
       [15] = Sound profiles

 [3] = Group Policy | Additional optional ability to configure GP with your own parameters

       It is used individually if necessary, since the entire set of GP settings is used in all scripts independently through LGPO.exe

 [4] = Windows Update | Windows Update related parameter group
 [5] = Maintenance    | A group of options and actions related to Maintenance Windows and updating offline.

 [100] = Restart Computer | Forced

 [999] = Restoration | Restores all parameters of the AutoSettingsPS complex from all menus according to the preset: \QuickPresets.txt (from the second part of the preset for Restore)


    ╔═════╗
 ■══╝  2  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Description of the general structure of both presets: \Presets.txt and \QuickPresets.txt

 Main Preset \Presets.txt

 It includes all possible settings to configure some menus and scripts to your preferences, from which you can check the current status.
 You can set your own paths for the location of folders, your icons, your time synchronization servers, and exclude some groups of settings from execution.
 or exclude entirely scripts for the menu [1] = Configs-Checks

 Second preset: \QuickPresets.txt ([0] = Quick Settings) to specify a complete set for quick setup from almost all of the AutoSettingsPS menus.
 All settings are performed in a single pass. Similar to menu [1] = Configs-Checks
 When using it, the scripts themselves also take parameters from the preset \Presets.txt

 That is, it doesn’t matter how you started the execution of any action, through Quick Settings or Configs-Checks or SelfMenu manually,
 settings will be taken from the main current presets file: \Presets*.txt


    ╔═════╗
 ■══╝  3  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ The structure of folders and files AutoSettingsPS.

 All files must be in UTF-8 encoding! Including for your settings! Besides .Reg files encoded with UTF-16

 Preset file for basic settings: \Presets.txt         Details inside
 Preset file for quick settings: \QuickPresets.txt    Details inside

 Files: ps1, cmd, bat, reg with their settings put in a folder: \Files\CustomFiles  More in \QuickPresets.txt

 My dark theme file for PowerShell ISE: \Files\DarkTheme-for-PS-ISE.StorableColorTheme.ps1xml (Since all scripts need to be edited in the editor for PS, for example, ISE)

 1. The batch file _Start_AutoSettingsPS.bat launches the AutoSettings.lnk Shortcut, which launches the main script.
    In the setting of the shortcut options listed PowerShell startup and configuration console: size, font, color, clipboard.

 2. Main script:  \Files\_Tools\AutoSettings.ps1
    It lists all the main global variables, performing all checks, starting/restarting all menus and scripts.

 3. Files of all menus: \Files\_Tools\Menu

 4. Configuring Windows goes through the functions in the folder: \Files\_Tools\Scripts, The function headers contain basic information.
    In these functions, you can remove / comment, replace unnecessary, or add parameters to execute.

 5. Functions that provide the execution of actions for everything and output of information are located in the folder: \Files\_Tools\Scripts-Management

 6. Folder for update files: \Files\Updates   (.cab or .msu)

 7. Folder for Group Policy settings files via LGPO.exe: \Files\GP
    Settings are saved in it when you create your Group Policy settings file from the menu for the GP.
    There are no prepared GP parameters for example. All GP settings are applied through the parameters in the functions.

 8. Folder for Appx/Msix/AppxBundle/MsixBundle/Xml/Cer files: \Files\Appx


    ╔═════╗
 ■══╝  4  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ The used set of utilities for the possibility of implementing some necessary actions:

 1. Handle.exe - Free Utility v.4.22 for use by command line from MS
    To identify processes that lock a folder.
    You can read and download here: https://technet.microsoft.com/en-us/sysinternals/handle.aspx

 2. 7z.exe - Console free version of the archiver 7-Zip 22.01 x86
    Used here to extract the necessary files from service packs or unpack CAB and MSU.
    You can read and download here: http://www.7-zip.org/

 3. smartctl.exe - Free Utility v7.3 x86 for use by the command line from ballen4705, chrfranke, dipohl
    Needed for get information and SMART HDD and SSD drives.
    Used here to determine the SSD drives in the system, which can be identified through PS as HDD
    But also can not give a 100% guarantee of determining the SSD, due to problematic drivers or RAID arrays.
    You can read and download here: https://sourceforge.net/projects/smartmontools/

 4. LGPO.exe v3.0 - The official utility for using the command line from MS.
    Helps automate the configuration and backups of Group Policy, audit and security settings.
    Used here to add or reset individual settings or entire sections in Group Policy.
    Description: https://blogs.technet.microsoft.com/secguide/2016/09/23/lgpo-exe-v2-0-pre-release-support-for-mlgpo-and-reg_qword/
    Download: https://www.microsoft.com/en-us/download/details.aspx?id=55319

 5. ffmpeg.exe - Free Console Utility x86 v4.3.1
    I compilationed from the source code, with a minimum set of functions to get the minimum size of an exe file (977Kb)
    With functions only decrease the volume of wav files, and get the volume level from them.
    You can read and download here: https://ffmpeg.org/

 I implemented everything else through the functions, means and capabilities of the PowerShell language, using .NET Csharp code (C#)
 I used the most understandable algorithms, the type of recording, and the maximum possible description to all lines of code.
 I studied PowerShell while writing functions. And a little Csharp code (C#), since there is nothing suitable, necessary, or, especially, completely ready.
 This is my first introduction to PowerShell and Csharp.


    ╔═════╗
 ■══╝  5  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ The scripts determine the bit depth of Windows and take this into account when setting the parameters. When installing cab files, the Windows version will be taken into account.
   The language of the system does not matter. System variables are used everywhere, and they are possible when specified in presets.
   The script defines any rights at startup: TI, System, Admin, User. It will be allowed only with Admin rights.

 Implemented important necessary features for AutoSettingsPS and RepackWIMPS scripts. Details are described in the function headers.
 Only they are not translated into English, the main ones are:

 1. Using (connecting a token) Impersonation of the current process for TrustedInstaller or System,
    with the inclusion of all privileges, without restarting, without utilities (Function: Token-Impersonate)
 2. Adding privileges to the current process, without utilities (Function: Token-Privileges)
 3. Starting processes with TrustedInstaller or System rights, the privileges are original for these processes, without utilities (Function: Start-ParentProcess)
    Example of importing registry settings from test.reg file from the "\Files\CustomFiles" folder under system rights
    (write this line, for example, in a script \Files\CustomFiles\1_Script_Test.ps1, without added _TI or _SYS):
      Start-ParentProcess -RunAs SYS -CurrentDirectory .\Files\CustomFiles -CmdLine 'reg import "test.reg"' -Wait
    Such an option, since under impersonate (ps1 files with the name ..._ TI or ..._ SYS) there is no access when using reg imoprt
    (privileges in this case and some others are not transferred, such conditions for differentiation of rights in the system).
 4. Convenient coloring of console output, when specifying in one line, without utilities (Function: Write-HostColor)
 5. Gaining access to registry keys or files in any cases, except for blocking by drivers, without utilities (Function: Set-OwnerAndAccess)
    To temporarily gain access, a separate preservation of the original SDDL is used, before gaining access, then returning rights upon completion by the same function.
 6. Saving console output in the same form to an HTML file, without utilities (Function: Save-HtmlLog)
 7. Configuring the Set-Reg registry, Set-LGP group policies, Set-Tsk tasks, Set-Svc services, Set-Drv drivers, which use the above-described functions according to the situation automatically,
    they allow you to specify the functions of what you need to do as a standard cmdlet, without thinking about the absence of a partition, access, etc.
    All that is needed will be done automatically. A temporary change of rights occurs only in cases where there is no access for anyone, that is, Impersonate for TI did not solve the problem.
    And the result of the execution is displayed, that is, it is immediately visible whether the parameter is applied or not.
    Almost all actions are performed through .NET commands directly, not by cmdlets.
 8. The principle of the convenient creation of any menu has been developed, with any desired coloring of the output, the results of functions, variables inside the menu.
    There is a separate description for the structure of all menus (No translation into English)
 9. Other functions, including those using the ones described above.

 Functions are written on the same or similar principle, for ease of understanding and use.
 Including for the possibility of combining all of them into one common project for automatic system configuration, or image servicing.

 The color, font size, window size and buffer for the console are specified in the shortcut parameters for running the script.
 System Preferences console on what does not influence or change.
 The colors indicated in the Shortcut are customized by me. Since the default colors for consoles in the system is a complete disappointment.

 The output format is designed to maximize information content, but at the same time maximize compactness.
 One principle of using output highlighting is slightly different for displaying menus and for output at runtime:
  When executing an Error - Red and Yellow; Recovery - magenta, Information - White, not important information - dark gray or dark turquoise (DarkCyan)
  The result is positive - Green, Negative - Yellow. For Menu, yellow also shows default parameter or changed, and menu names.
  The essence is in contrasts for a better perception.


    ╔═════╗
 ■══╝  6  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Description of some menu items and features.

 Quick-Settings Menu - Apply or restore all necessary settings at once. More details in the preset file for quick settings: QuickPresets.txt
 The AutoSettingsPS script was made precisely for the sake of this point in the main and therefore is called so!

 Parameters from the Presets.txt main preset are also used for quick setup.
 If in the QuickPresets.txt preset for Quick-Settings, a complete reset of Group Policy (GP) will be used to reset all settings (only .pol files are removed),
 it doesn’t matter in which order, at the end of all the actions, the GP settings from other functions will not be applied.
 Since there are nuances of managing GP settings, including through lgpo.exe
 And it makes no sense, since the GP are reset, why is there something else to configure in GP.

 If the batch file to start the main script _Start_AutoSettingsPS.bat is started with the key: /RunQuickSettings,
 it will autostart Quick-Settings from the first item, then stop. Exit - after pressing any key.
 To close the script after completion, you need to add one more parameter: /QuickExit
 Example: "D:\AutoSettingsPS\_Start_AutoSettingsPS.bat" /RunQuickSettings /QuickExit  (you need to run as administrator, otherwise there will be a request for rights)


    ╔═════╗
 ■══╝  7  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Group Policies using LGPO.exe v3.0

 The LGPO.exe utility configures the GP, similar to manual configuration in the GP editor "gpedit.msc".
 Removes or Adds individual settings to already configured policies. If the parameter exists, then replaces it.

 In some cases, if you specify the removal of a parameter, the GP editor can accept the parameter configured to "Disabled"
 This is correct, as some parameters have the same effect with "Not configured" and "Disabled".
 To make it considered "Not configured" in such situations, you must specify the removal of all parameters in that section.
 But you need to understand that if there are parameters that you do not need to remove, then you do not need to clean the entire section!
 But you can do the removal of the partition, and then add the desired parameter back, which should be there.

 Therefore, if for LGPO you specify the removal of the parameter, then this behavior is recorded in the Registry.pol file
 And if you add such a parameter through the registry, then when updating the GP this parameter will be removed.
 The same thing is in the opposite direction. To erase commands for removing registry values or clearing registry keys from Registry.pol,
 It was necessary to reset all GPs through the menu. Now it is not necessary in cases where there are no other parameters in the section,
 since other commands are now used for these actions in the lgpo.exe use function.

 In the new implementation, the Set-LGP function (for lgpo) added an automatic check for the absence of parameters in the section,
 and if there are no parameters, adding a clear of all the settings associated with this section - This solves 98% of the GP displaying as "Disabled."
 Not all, because in those registry keys for policies there may be parameters specified not through the GP. Or not all parameters are indicated for removing.

 Parameters are accepted for the Set-LGP (lgpo) function only for sections with the name ... \Policies\ ... and in the HKLM or HKCU registry keys
 If you add HKLM and HKCU keys to any other place, then resetting the GP does not remove these parameters, therefore, did not enable this opportunity.

 The Set-LGP function (for LGPO) will report all inappropriate paths. And it takes over the parameters as in standard cmdlets and Set-Reg function + other opportunity.
 The script for using the LGPO file, if an error occurs during setup, will copy the problem file, with the GP parameters for lgpo, to the script folder,
 so that you can understand which parameter was wrong. All actions are displayed, correct and erroneous.

 The Set-LGP function (for LGPO) performs uninstallation or installation as a regular cmdlet and as a Set-Reg function
 and additionally writes a parameter to the global variable for LGPO, which is everywhere indicated for use at the very end of the settings.
 If there is no GP in the system, then there will simply be no GP applied, and the parameters themselves are always and immediately configured directly in the registry.


    ╔═════╗
 ■══╝  8  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Management and execution of Windows maintenance (Description is old from a batch file for 1607, but slightly corrected, and is given for understanding)


 Ability to disable Windows auto-maintenance and manual start.
 Who does not like the frequency of execution and the tasks themselves during maintenance.

 There is no need to turn it off if manual maintenance Will not be executed!
 It is enough to disable unnecessary Windows actions when configuring in other menus, and this will already reduce the set and frequency of servicing actions.

 It uses tasks with hidden "MaintenanceSettings" options.
 After maintenance is denied, you cannot start these tasks either manually or start maintenance from the maintenance center.
 Some tasks are already disabled by the script, + part can be disabled through any of your settings.
 Some are disabled on the system initially, and will be enabled by services as needed.

 I wrote down the entire list of tasks used by the auto-maintenance of Windows 10 1607.
 The list is based on the system after RepackWIM; there may still be tasks on a clean Windows.
 They are performed depending on the conditions, not all each time, but still too much.
 Often load the system, drain the battery, etc. for the sake of ~1% performance and collection of your data, MS "cares" about "you":

   1: "Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319" (Checking images at boot, Mscorsvw.exe, Ngen.exe, NGenTask.exe)
   2: "Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319 64" (Checking images at boot, Mscorsvw.exe, Ngen.exe, NGenTask.exe)
   3: "Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319 64 Critical" (Recompilation of images, Mscorsvw.exe, Ngen.exe, NGenTask.exe)
   4: "Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319 Critical" (Recompilation of images, Mscorsvw.exe, Ngen.exe, NGenTask.exe)
   5: "Microsoft\Windows\AppID\SmartScreenSpecific" (Data acquisition for SmartScreen and MS)
   6: "Microsoft\Windows\Application Experience\ProgramDataUpdater" (data collection for MS, for program compatibility assistant)
   7: "Microsoft\Windows\Application Experience\StartupAppTask" (evaluation of startup list and warnings)
   8: "Microsoft\Windows\ApplicationData\CleanupTemporaryState" (cleaning up temporary Windows Store application files)
   9: "Microsoft\Windows\ApplicationData\DsSvcCleanup" (dstokenclean.exe Windows Store Data Sharing maintenance)
  10: "Microsoft\Windows\AppxDeploymentClient\Pre-staged app cleanup" (cleaning Windows Store apps)
  11: "Microsoft\Windows\Chkdsk\ProactiveScan" (Chkdsk, pstask.dll Checking and Troubleshooting NTFS Issues)
  12: "Microsoft\Windows\Customer Experience Improvement Program\KernelCeipTask" (data collection for MS)
  13: "Microsoft\Windows\Customer Experience Improvement Program\UsbCeip" (data collection for MS)
  14: "Microsoft\Windows\Defrag\ScheduledDefrag" (defrag.exe Defragment SSD and HDD, TRIM SSD)
  15: "Microsoft\Windows\Device Setup\Metadata Refresh" (data collection for MS, update metadata for devices)
  16: "Microsoft\Windows\Diagnosis\Scheduled" (sdiagschd.dll System Verification Scenarios)
  17: "Microsoft\Windows\DiskCleanup\SilentCleanup" (cleaning the system drive when there is not enough space and when idle, cleanmgr.exe)
  18: "Microsoft\Windows\DiskDiagnostic\Microsoft-Windows-DiskDiagnosticDataCollector" (data collection for MS)
  19: "Microsoft\Windows\DiskFootprint\Diagnostics" (data collection for MS, drive usage evaluation)
  20: "Microsoft\Windows\DiskFootprint\StorageSense" (data collection for MS, drive usage evaluation for Windows Store)
  21: "Microsoft\Windows\ErrorDetails\ErrorDetailsUpdate" (data collection for MS)
  22: "Microsoft\Windows\Feedback\Siuf\DmClient" (data collection for MS)
  23: "Microsoft\Windows\FileHistory\File History (maintenance mode)" (file archiving maintenance)
  24: "Microsoft\Windows\LanguageComponentsInstaller\Uninstallation" (LanguageComponentsInstaller.dll Removing unnecessary language features)
  25: "Microsoft\Windows\License Manager\TempSignedLicenseExchange" (license check for Windows Store applications)
  26: "Microsoft\Windows\Maintenance\WinSAT" (system performance measurement)
  27: "Microsoft\Windows\MemoryDiagnostic\RunFullMemoryDiagnostic" (memory check)
  28: "Microsoft\Windows\MUI\LPRemove" (lpremove.exe Cleaning unnecessary languages and their parameters)
  29: "Microsoft\Windows\PI\Sqm-Tasks"  (data collection for MS, Trusted Platform Module)
  30: "Microsoft\Windows\Plug and Play\Plug and Play Cleanup" (cleanmgr.exe removal of old unnecessary drivers included in disk cleanup)
  31: "Microsoft\Windows\Power Efficiency Diagnostics\AnalyzeSystem" (data collection for MS, checking energy consumption)
  32: "Microsoft\Windows\RecoveryEnvironment\VerifyWinRE" (checking Windows recovery environment)
  33: "Microsoft\Windows\Registry\RegIdleBackup" (Backup registry)
  34: "Microsoft\Windows\Servicing\StartComponentCleanup" (TiWorker.exe, WinSxS maintenance, removal of old updates and components, included in disk cleanup)
  35: "Microsoft\Windows\SettingSync\BackgroundUploadTask" (File Sync maintenance)
  36: "Microsoft\Windows\SettingSync\BackupTask" (File Sync maintenance)
  37: "Microsoft\Windows\Setup\SetupCleanupTask" (Removes files from a previous installation of Windows)
  38: "Microsoft\Windows\SharedPC\Account Cleanup" (Clearing old accounts for remote access)
  39: "Microsoft\Windows\Shell\IndexerAutomaticMaintenance"  (Search Index Update)
  40: "Microsoft\Windows\Sysmain\HybridDriveCachePrepopulate" (hybrid disk cache maintenance)
  41: "Microsoft\Windows\Sysmain\HybridDriveCacheRebalance" (hybrid disk cache maintenance)
  42: "Microsoft\Windows\Sysmain\ResPriStaticDbSync" (data collection for MS, sync your data list)
  43: "Microsoft\Windows\Sysmain\WsSwapAssessmentTask" (data collection for MS, Swapfile.sys evaluation for Windows Store applications)
  44: "Microsoft\Windows\SystemRestore\SR" (srtasks.exe creating recovery points)
  45: "Microsoft\Windows\Time Synchronization\SynchronizeTime" (w32tm.exe time synchronization)
  46: "Microsoft\Windows\Time Zone\SynchronizeTimeZone" (tzsync.exe, Time zone synchronization)
  47: "Microsoft\Windows\UpdateOrchestrator\Maintenance Install" (scheduled update installation)
  48: "Microsoft\Windows\WOF\WIM-Hash-Validation" (maintenance connected WIM files)

 Most users who are really needed or rarely needed are just a few:
 Generation of .NET Framework images for programs and components (compilation of images with machine code for programs to speed up their launch and operation).
 Drive cleanup from old updates, drivers and temporary files.
 Time synchronization, defragmentation, TRIM SSD drives and NTFS verification.

 These tasks are in groups:
 Performance and configuration (important or desirable after installing/replacing software, or system updates):
   1: "Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319" (Checking x86 images at boot, Mscorsvw.exe, Ngen.exe, NGenTask.exe)
   2: "Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319 64" (Checking x64 images on boot, Mscorsvw.exe, Ngen.exe, NGenTask.exe)
   3: "Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319 64 Critical" (Recompilation of x64 images, Mscorsvw.exe, Ngen.exe, NGenTask.exe)
   4: "Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319 Critical" (Recompilation of x86 images, Mscorsvw.exe, Ngen.exe, NGenTask.exe)
  14: "Microsoft\Windows\Defrag\ScheduledDefrag" (defrag.exe Defragment SSD and HDD + TRIM SSD, better to doing after cleaning the disk)
  45: "Microsoft\Windows\Time Synchronization\SynchronizeTime" (w32tm.exe time synchronization)

 Drive cleaning (it makes at least some sense, not more than 1 time per month, manually all these 3 actions are done through cleanmgr.exe):
  17: "Microsoft\Windows\DiskCleanup\SilentCleanup" (cleanmgr.exe /autoclean /d %systemdrive% - auto-clean system disk: temporary files, updates, drivers, etc.)
  30: "Microsoft\Windows\Plug and Play\Plug and Play Cleanup" (cleanmgr.exe removal of old unnecessary drivers, included in disk cleanup)
  34: "Microsoft\Windows\Servicing\StartComponentCleanup" (TiWorker.exe, WinSxS maintenance, removal of old updates and components, included in disk cleanup)

 Troubleshooting (usually checked, if there is a problem, through the properties of the disk):
  11: "Microsoft\Windows\Chkdsk\ProactiveScan" (Chkdsk, pstask.dll Checking and Troubleshooting NTFS Issues)


 From all this, in the end, we have 2 options for manual actions that make sense for performance and after updates:
  Option 1: Generating a .NET images for programm using .NET (if there were updates to programs or Windows, or new software, Critical action!)
  Option 2: Update system -> synchronize time -> generate .NET images! -> clean up drive -> defragment the HDD and/or TRIM SSD.
 It’s not necessary to even do the 2nd option often, only .NET is important, and if you don’t do this, Windows will just slow down.

 As a result, Windows will not torment the hardware, including during downtime.
 This does not affect auto-checking and manual installation of updates, and other tasks not included in the list above.
 If you do not disable Superfetch, then it will sometimes analyze the disk during downtime, the process: svchost (LocalSystemNetworkRestricted -p)
 From the pros - you choose the time for these time-consuming and long maintenance operations. Minus - you need to do it yourself =)

 General features for using updates and maintenance:
 Exclude defragment their SSD drives by separating disk optimization tasks. They will replace the original task, and will be used by the Windows maintenance or on their own.
 Disable updates and check for Windows updates completely, and manually update from a folder.
 You can choose the time for updates and important maintenance. It is enough to do the cleaning once every half a year, but all according to the situation.


 Description of menu options "Maintenance".
 Not all options need to be done often, but it makes sense to follow the sequence.
 For example, do defragmentation at the very end, do disk cleanup after updates (you can also do without updates), etc.

  1. Manual update menu

     To use, you need to download the MSU or CAB update files and drop them into the \Files\Updates folder, that's all.

     The easiest way is to download via ready-made links from the ru-board forum, guys are laying out there.
     Here's an example from FFoldz
     http://forum.ru-board.com/topic.cgi?forum=62&topic=31153&start=20#9

     The .msu and .cab files are searched in the \Files\Updates folder, and are installed by the DISM utility
     Standard procedure provided by MS for offline maintenance.

     Disabled Windows update services and tasks do not interfere with such an installation!

     The names of the files themselves are not important. The displayed information is taken from them,
     also displays the status and whether they are suitable for the current Windows.

     For MSU files, only bit depth is checked.
     Since extracting cab from msu and getting full information from cab for display will be too slow every time.

  2. Menu for saving drivers for the ability to restore them after a clean installation of Windows

  4. .NET Framework Image Generation (Ngen.exe)

     Creates .NET images that were requested by installed programs or Windows components that use the .NET Framework

     This speeds up the startup and operation of these components.
     Components use ready-made commands from generated .NET images to work, and do not generate them every time from scratch.
     Not all programs use .NET to work, and they do not need image generation.
     The procedure is standard, described on the MS website.

  5. Cleaning the WinSxS folder and system drive

     First, use the command: Dism /Online /Cleanup-Image /StartComponentCleanup
     for clean old updates in WinSxS without the "30 day delay" rule, like cleanmgr.exe
     Then the standard command for %windir%\system32\cleanmgr.exe
     Automatically removes old updates, old drivers, cleans temporary folders, etc.
     But here in the script specified for skipping cleaning:
       Downloads folder, trash, updates, icon cache, user file history, branchcache

  6. Forced time synchronization, with the addition of your synchronization servers.
     The result of setting the synchronized time may be delayed.
     Need internet.

  8. Local Drive Optimization Menu

     2 separate variables are created, with drive letters in the system %HDDdrives% and %SSDdrives%, and on this basis everything happens further.

     Separate tasks, standard parameters:
     For all SSDs - only performs TRIM:       %windir%\system32\defrag.exe %SSDdrives% -h -l
     For all HDDs - performs defragmentation: %windir%\system32\defrag.exe %HDDdrives% -h -o -$

     Tasks will be used by Windows maintenance instead of the standard task, if you do not prohibit, or on your own.
     Or if you manually run Windows maintenance. This is optional.



    ╔═════╗
 ■══╝  9  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Transfer personal folders of the current user to any other place of your choice.

 Folders: Videos, Documents, Downloads, Pictures, Music, Desktop, Saved Games
 To copy files, the robocopy system utility is used to ensure reliability and track execution results and errors.

 The script doesn’t care if the folder itself or the value in the registry exists, everything necessary will be configured.
 This is convenient if you messed up the settings or accidentally removed folder, or something else.
 The desktop.ini file is always created from scratch with the necessary attributes and parameters by default.
 Also, standard attributes and security parameters are set on the folder, as in the original + additional parameters.
 Options for prohibiting non-administrator removal of a folder or displaying a UAC request.
 Changing the location of folders is carried out similarly to a manual action through
 change of location in the conductor + additional actions.

 If you plan to change the location of folders for several users (accounts) in one place,
 you must specify a subfolder with the user name in the path so that the folders do not turn out to be the same for different users!
 Example: D:\%UserName% or C:\111111\%UserName%
 You can also do this with a single user.



    ╔══════╗
 ■══╝  10  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Transfer the "temp" folder of the current user to any other place of your choice.

 And creating a symbolic link, in the default location, which will redirect to the new location.
 The link is needed for programs that force the default location.
 All programs must be closed before changing !!!
 If the folder is still blocked, then the processes that block the folder will be forcibly closed.

 One minus, if you transfer the folder to another partition or disk that is different from the system one, then the evaluation utility
 system performance "winsat.exe" will not be able to analyze the disk size and will not give the test result!
 When transferring to a RAM disk, which is created every time from scratch, there will be no sense in assigning rights.
 And you need to specify the rights in the settings of the RAM disk itself, or do automation of setting the rights to folders at system startup.
 If you transfer folders for all accounts, start and transfer separately for each account.

 You can specify your path to transfer the folder in \Presets.txt file




    ╔══════╗
 ■══╝  11  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Transfer the system folder "temp" to any other place according to your desire.

 Similarly with the "temp" folder of the current user.
 It is better to specify the destination path different for the Temp system folder and for users!
 But the settings allow you to specify in one folder!

 Different temp folders are made by MS for security, since one is a system one, for system applications, and for execution by applications with elevated rights.
 And the second folder is for the user to executing under his reduced or elevated rights.
 Therefore, in the script when restoring folder locations, all this is taken into account, and original rights are assigned everywhere, as intended by MS.
 And when changing the location, special access rights are set so that applications work correctly with temporary files without having elevated rights.
 And you can remove folder itself only with administrator rights.
 If your UAC is always disabled, then these nuances are no longer important, since everything is already allowed.

 You can specify your path to transfer the folder in \Presets.txt file

 You can specify one folder for all temp, but it is better not to violate the initial conditions of MS


    ╔══════╗
 ■══╝  12  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Fast boot settings

 Fast booting on shutdown uses hibernation mode.
 It is needed for fast booting of Windows and used programs.
 But this often leads to various problems, including due to lack of reboot.
 And if you use a lot of heavy programs, then fast booting will be slower than regular booting.
 By default, the parameter has values = 1 (Enabled) and does not apply to hibernation, but depends on it!




    ╔══════╗
 ■══╝  13  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Setting to wake up the computer

 Configuring computer wakeup to perform scheduled Windows auto-maintenance.
 Maintenance - transferring collected data and reports, updating search indexing,
 boot optimization, cleaning the system drive, etc. Assigned by default at night.
 If disabled, then defragmentation, file system maintenance
 and other really important actions will be performed as necessary, during idle time, as usual.
 But you can disable maintenance and execute it manually from the maintenance menu in the script.



    ╔══════╗
 ■══╝  14  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ IPv6 Internet Protocol Setting

 If disable it, only the loopback for programs over IPv4 remains.
 Disabling removes 99% of the DNS server spam and warnings in the event log from DNS Client Events (wpad, etc.)
 If there are no warnings from this spam in the event log in the warning section,
 or if it doesn’t bother you, then do not disable it.
 If you are not using IPv6, then disabling should not cause problems.
 By default, this parameter is not, but its value is considered = 0 (enabled)



    ╔══════╗
 ■══╝  15  ╚══════════════════════════════════════════════════════════════════════════════════════════════■

 ■ Menu for Managing Modern Applications Apps/Appx in Windows 10 x64/x86 1809-2004

 Is used for Installing/Re-registering/Uninstalling/Downloading Modern Applications (Apps/Appx).

 Apps in the script means - Installed applications
 Appx in the script means - Application Appx Files (Appx/Msix/AppxBundle/MsixBundle)

 Uninstalling Apps for all users, files remain only for system Apps!
 Therefore, Store Apps can be installed only through the Store or after downloading the files. Or if you put them yourself in the folder for Appx.
 The script picks up the files of licenses .xml and certificates .cer, certificates are installed only during installation, then deletes (this is done on purpose).
 To prevent the script from deleting certificates, you need to manually install them yourself. Then the script thinks that you need an installed certificate.

 The beginning of the License xml file name must be the same as the beginning of the Appx file name before the "_" character, if there is one in the Appx file name.
 Example: File: abc.appx or abc_ffff.appx; License: abc_License.xml or abc.xml, that is, the search will be conducted by "abc", the following characters are not important.
 A complete offline installation of Appx, without a network connection, requires an offline xml license and all dependent Framework specified in its manifest.

 You can add your own in the same way. A file with a list of installed Apps can be obtained from the menu.
 If the application is installed, then when you select "install", a re-registration occurs, it fixes various problems with the application.
 You can also specify system applications that are blocked for Uninstall. Everything is at your own risk!
 They can be restored, but there is always a chance that they will not be restored! But we didn't have such situations.

 Uninstall is performed by standard PowerShell cmdlets, after unlocking them in the StateRepository-Machine.srd database
 Restores a blocking trigger in the database after removal it.
 Removing shortcuts from the desktop and taskbar, the names and number of shortcuts do not matter.
 The registry subkeys that are named PackageFamilyName (Store) are added to the registry key: ...\AppxAllUserStore\Deprovisioned (to exclude their autoinstallation)
 Disabling the installation of system Apps by removing keys in ...\AppxAllUserStore\InboxApplications, access rights, clearing the restoring parameters by the task.
 The necessary set of measures to achieve an ideal result.

 The "AutoClean task" runs before the user logs on, does not use files. All commands are specified within the task, execution speed 0.1-0.3 sec
 This is necessary so that after the update is complete and during the first boot of Windows, before the user logs on for the first time,
 remove the parameters of the updated and Uninstalled system Apps restored by the update - This is very important.
 Otherwise, some will be installed back, but due to long attempts to install the rest of the blocked Apps,
 Windows will not let the shell (explorer) start (Up to 10 minutes black screen every boot).
 It does not start manually either! You need to either install all system Apps back, or remove the parameters!
 The task can be changed, disabled, removed only under system rights, it was done so on purpose! But there is a possibility to Run the task.
 The script checks the task every time you perform any action with any Apps, and itself Creates/Modifies/Deletes the task if necessary.

 Do not remove these 3 Apps:
 1. Microsoft.Windows.StartMenuExperienceHost  # Start Menu (2004) (if you uninstall it, there will be no Start Menu, you need a replacement, but when you try to run it: win or ctrl+win, there will be an error. To avoid the error, you must disable Appx management services, and these consequences must be checked)
 2. Microsoft.Windows.ShellExperienceHost      # Action Center (if you uninstall it, there will be no notification curtains)
 3. windows.immersivecontrolpanel              # UWP System Settings (if you uninstall it there will be no Modern Settings)

 These 2 are debatable:
 1. Microsoft.Windows.CloudExperienceHost      # Required to create a new user account (Required for the first login to an account, unless the privacy settings are preset in NTUSER.DAT or there is a prohibition on running these settings in the GP)
 2. E2A4F912-2574-4A75-9BB0-0D023378592B       # AppResolverUX Needed for managing Apps in some cases not known to me.

 Uninstallation by script does not lead to errors or violation of Windows integrity! Apps will be updated but not installed back!
 When installing system Apps through a script, everything is restored back. The algorithms are universal and work on versions 1809-2009 (20H2).
 The renamed system Apps folders will be skipped, with a message about this. so you can restore them only by what you changed them.

 If the downloaded Appx is not installed, it means that he is missing something, usually Framework dependent packages, either does not fit the system. And other factors.
 You need to look at the error description and by logs. There are a lot of nuances with Apps/Appx.

                                                    ──┐
 [10] = Uninstall All | Specified to Uninstall Apps   │ (Group of Options for managing Apps)
 [20] = Install All   | Specified to Install Apps     │ ◄ Re-registration/Registration (If not found, looks for Appx in the script folder and installs, determines by the folder name)
                                                    ──┘
                                                    ──┐
 [30] = Download All  | Customized for Download Appx  │ (Group of Options for managing Appx)
 [40] = Install All   | Found Appx in Subfolders      │
 [50] = Uninstall All | Found/Configured Appx         │ ◄ "Uninstalling" the Appx configured for downloading, downloaded and installed (the name is determined by the manifest inside the appx) Here Keep in mind, for example, if you just download the Store and it will be installed, then this option will Uninstall the installed Store of any version!
 [60] = Clean Folder  | Files\Appx\ from subfolders   │ ◄ Deleting subfolders with files
                                                    ──┘
                                                    ──┐
 [80] = Show Names    | for AutoСlean + Apps Problems │ ◄ Displays information on the restored parameters of Uninstalled system applications, according to the status of the "AutoClean task", and prepared (Staged), but not registered new versions of Apps
 [800] = Clean Parameters                             │ ◄ Performs deletes parameters to prevent installation of Uninstalled system Apps. The task does the same. (Just in case, mainly to check the completion of the task)
 [222] = Fix Apps Problems                            │ ◄ Attempting to register (Staged) but not registered new versions of Apps. (Sometimes the application was unable to update to the end and may stop working altogether, this is a bug) But It may not help, since not all problems are known to me.
                                                    ──┘

 Some versions of Appx support certain versions of Windows. This has become especially important since the release of Windows 11. You wouldn't know it before you downloaded it.
 For the main Appx file, you can specify which version you want the script to download or select from before/after the specified version.
 Examples of specifying versions are already specified in the Presets.txt file for the Appx files. If no suitable version is found, it will skip the download and all its dependent Appx.

 Example: ? 5.0.0.1 - specifies to select for W11 this version or newer, and for W10 the latest version but older than this one ("Question" Mark)
 Example: < 5.0.0.1 - specifies to select the latest version older than this one ("Less-Than" Sign)
 Example: > 5.0.0.1 - specifies to select the latest version newer than this one ("Greater-Than" Sign)
 Example:   5.0.0.1 - specifies to select this version (without the sign)

 No version - the latest version is selected



    ╔══════╗
 ■══╝  16  ╚══════════════════════════════════════════════════════════════════════════════════════════════■


 ■ Setting up multiple enabled local/domain accounts. Which have been logged in at least once (they will have .DAT files of the registry hives).
   The current account and partially default profile will always be customizable. The main menu shows the names of the accounts that will be fully configured!

 When setting up other accounts at one time, you can't pin folders in Explorer's "Quick Access". I was able to make everything else customizable.
 To move user folders for other accounts, you need to have the variable %UserName% at the end of the path in the preset. Otherwise there will be a setting skip.
 Since the locations of these folders in the end must be different.

 When setting up, it is better that other accounts are not logged in! So that nothing could interfere with the configuration.
 Immediately after setup, you can log in to these accounts or create other accounts. If the account was logged in, you have to re-login to it. It is better, of course, to reboot.

 Setting method:
 1. When you run the script, a global variable is created with all local/domain accounts: SID, Name, profile location (taken from the registry, so it doesn't matter if the name or location has been changed).
    The script then uses this data.

 2. The registry hives are loaded for all selected local/domain accounts at once, if they are not logged in. By the same paths as Windows does, only without the temporary symbolic link to Classes, because of the restriction.
    The script itself redirects to Classes. The hives are not unloaded! When you login to such an account, Windows itself unloads these hives and reloads them again, since the paths are the same.
    For the default profile, the Registry hive is loaded only when it is first configured, and is unloaded at the end of the script, so as not to block the hive file.
    If the default profile will only be partially configured, its hive is loaded during configuration and then immediately unloaded, each time displaying this action.
    Partial default profile customization is needed when the current Windows setup affects accounts that will be created in the future.

 3. When configuring, if specified to configure other accounts, Set-Reg and Set-LGP redirect all HKCU to all HKU\SID, and all HKCU\Software\Classes to HKU\SID_Classes.
    No Classes will be configured for the default profile, there is no hive and it makes no sense without the right SID.
    Each time, the presence of a loaded hive If it is not there, they try to load it once.
    If the hive fails to load for any reason, the hive will be removed from checking and configuring, and will be skipped in the future.

 4. Changed all functions that affect registry keys in HKCU and profile folders when configured.
    While performing the functions, all the actions will be repeated in turn for all the specified account profiles: folders and registry keys.




