PowerShell: Automating Process of Setting Up a New Windows Machine

# Step -2: Creating a New Virtual Machine
# Example A: Hyper-V 

# Compulsory variables
$hyperVHost='hypervHost05'
$vmName='Windows2019GoldImage'
$parentDirectory='\\CLUSTER03\GuestVms'
$disk1Size='100GB'
$memoryAllocation='4GB'
$networkSwitch='Trunk'
$vlan='101'

# Optional variables
$disk2Size=$false # false value here means no disk2 creation
$cpuCount=2
$isoDirectory='\\NETSHARES\ISOs'
$isoFile="$isoDirectory\SW_DVD9_Win_Server_STD_CORE_2019_64Bit_English_DC_STD_MLF_X21-96581.ISO"

function createNewVm{
    param(
        $hyperVHost,
        $vmName,
        $parentDirectory,        
        $disk1Size='80GB',
        $disk2Size=$false,
        $memoryAllocation='4GB',
        $cpuCount=2,
        $isoFile,
        $networkSwitch,
        $vlan=$false        
        )
    $ErrorActionPreference='Stop'
    $vmFolder="$parentDirectory\$vmName"
    $vmDisk1="$vmFolder\$vmName`_c.vhdx"
    $vmDisk2="$vmFolder\$vmName`_d.vhdx"    
    $disk1Size/=1
    $memoryAllocation/=1
    if($disk2size){$disk2Size/=1}
    #Pre-empt this error
    #New-VHD : Cannot bind parameter 'SizeBytes'. Cannot convert value GB to type "System.UInt64". Error: "Input string
    #was not in a correct format."
    #At line:1 char:35
    #+ New-VHD -Path $vmDisk1 -SizeBytes $disk1Size -Dynamic
    #+                                   ~~~~~~~~~~
    #    + CategoryInfo          : InvalidArgument: (:) [New-VHD], ParameterBindingException
    #    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Vhd.PowerShell.Cmdlets.NewVhd
    #

    function confirmation($content,$testValue="I confirm",$maxAttempts=3){
                $confirmed=$false;
                $attempts=0;        
                $content|write-host
                write-host "Please review this content for accuracy.`r`n"
                while ($attempts -le $maxAttempts){
                    if($attempts++ -ge $maxAttempts){
                        write-host "A maximum number of attempts have reached. No confirmations received!`r`n"
                        break;
                        }
                    $userInput = Read-Host -Prompt "Please type in this value => $testValue <= to confirm";
                    if ($userInput.ToLower() -ne $testValue.ToLower()){
                        cls;
                        $content|write-host
                        write-host "Attempt number $attempts of $maxAttempts`: $userInput does not match $testValue. Try again..`r`n"
                        }else{
                            $confirmed=$true;
                            write-host "Confirmed!`r`n";
                            break;
                            }
                    }
                return $confirmed;
            }    
    
    $confirm=confirmation "Please verify these variables for accuracy:`nVM Name`t: $vmName`nVM Folder`t: $vmFolder`nVM Disk1`t: $disk1Size bytes`nVM Disk2`t: $disk2Size bytes`nVM RAM`t: $memoryAllocation bytes`nVM Network`t: $networkSwitch`nVM VLAN`t: $vlan"
    if($confirm){
        try{
            write-host 'Creating VM Folder...'
            if (!(test-path $vmFolder)){mkdir $vmFolder -force}

            write-host 'Creating virtual hard disk(s)...'
            if(!(test-path $vmDisk1)){New-VHD -Path $vmDisk1 -SizeBytes $disk1Size -Dynamic}
            if($disk2Size -and !(test-path $vmDisk2)){New-VHD -Path $vmDisk2 -SizeBytes $disk2Size -Dynamic}

            write-host 'Creating VM...'
            
            New-VM -Name $vmName `
                    -MemoryStartupBytes $memoryAllocation `
                    -BootDevice VHD `
                    -VHDPath $vmDisk1 `
                    -Path $vmFolder `
                    -Generation 2 `
                    -Switch $networkSwitch
            
            write-host "Adding CPU count as $cpuCount"
            SET-VMProcessor –VMName $vmName –count $cpuCount

            write-host 'Attaching 2nd disk if necessary'
            if($disk2Size){Add-VMHardDiskDrive -VMName $vmName -path $vmDisk2}

            write-host "Mapping ISO image to $isoFile..."
            Add-VMDvdDrive -VMName $vmName -Path $isoFile

            write-host "Checking VLAN assignment $vlan"
            if($vlan){Set-VMNetworkAdapterVlan -VMName $vmName -Access -VlanId $vlan}

            write-host "Starting VM $vmName..."
            Start-VM -Name $vmName

            write-host 'Connecting to new VM...'
            if ($env:computername -eq $(.{[void]($hyperVHost -match '([\w\-]+)\.{0,1}');$matches[1]})){
                invoke-expression "VMConnect.exe $env:computername $vmName"
                }
            else{
                write-host "Please RDP into the $env:computername Hyper-V host to run this command 'VMConnect.exe `$env:computername $vmName'"
                }
            return $true
            }
        catch{
            write-warning "$($error[0])"

            return $false
            }
        }
    else{
        write-host 'Cancelled.'
        }
}

createNewVm -hyperVHost $hyperVHost -vmName $vmName -parentDirectory $parentDirectory -disk1Size $disk1Size -disk2Size $disk2Size `
            -cpuCount $cpuCount -memoryAllocation $memoryAllocation -isoFile $isoFile -networkSwitch $networkSwitch -vlan $vlan
# Step -1: Enable Remove Desktop
function enableRemoteDesktop{
    Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -name 'fDenyTSConnections' -value 0
    Enable-NetFirewallRule -DisplayGroup 'Remote Desktop'
}
enableRemoteDesktop
# Step 0: Activate Windows
$licenseKey="XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
function activateWindows{
param(
[string]$key
)
$licensingService = get-wmiObject -query "select * from SoftwareLicensingService" -computername $env:computername;
$licensingService.InstallProductKey($key);
sleep 20;
$licensingService.RefreshLicenseStatus();
Get-CimInstance -ClassName SoftwareLicensingProduct|where {$_.PartialProductKey}|select Description, LicenseStatus
}
activateWindows;
# Step 1: Rename the local machine while remaining with its default workgroup
$newServerName="SOMENAME"
Rename-Computer -NewName $newServername -Force
Restart-Computer -Force
# Step 2: Find the OU of an intended peer server
$peerServername="SHEVER002"
Move-ADObject $peerServername -TargetPath "OU=Quarantine,DC=INTRANET,DC=KIMCONNECT,DC=COM" -WhatIf
# Step 3: Join new machine to domain
$newServername="SHERVER007"
$domain="INTRANET.KIMCONNECT.COM"
$desktopAdmin="Rambo"
$ouPath= "OU=Servers,DC=INTRANET,DC=KIMCONNECT,DC=COM"
$cred = Get-Credential "$domain`\$desktopAdmin"
add-computer -computername $newServername –Domain $domain -Credential $cred -OUPath $ouPath -restart –force
# Step 4: Install  Choco and update PowerShell
if (!(Get-Command choco.exe -ErrorAction SilentlyContinue)) {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))}
$packages = 'powershell','googlechrome','firefox','adobereader','7zip.install','javaruntime','putty.install','sysinternals','dotnet4.7'
ForEach ($package in $packages){choco install $package -y --ignore-checksums};
Restart-Computer -Force;
# Note: Use UpdateRemoteWindows, instead. That function will automate reboots and resuming updates. This updateLocalWindows is still requiring too much manual intervention.

# Step 5: Perform Windows Update
function updateLocalWindows{
# Prerequisites
function installPrerequisites{
#Import-Module PSWindowsUpdate -force;
#$psWindowsUpdateAvailable=Get-Module PSWindowsUpdate -EA SilentlyContinue;
$psWindowsUpdateAvailable=Get-Module -ListAvailable -Name PSWindowsUpdate -ErrorAction SilentlyContinue;
if (!($psWindowsUpdateAvailable)){
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false | Out-Null;
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted | Out-Null;
Install-Module PSWindowsUpdate -Confirm:$false -Force | Out-Null;
Import-Module PSWindowsUpdate -force | Out-Null;
}
catch{
"Prerequisites not met on $computer.";
}
}
}

function checkPendingReboot{
param([string]$computer=$ENV:computername)

function checkRegistry{
if (Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending" -EA Ignore) { return $true }
if (Get-Item "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -EA Ignore) { return $true }
if (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -EA Ignore) { return $true }
try {
$util = [wmiclass]"\\.\root\ccm\clientsdk:CCM_ClientUtilities"
$status = $util.DetermineIfRebootPending()
if(($status -ne $null) -and $status.RebootPending){
return $true
}
}catch{}
return $false
}

$localhost=$ENV:computername
if ($localHost -eq $computer){
$result=checkRegistry;
}else{
$result=Invoke-Command -ComputerName $computer -ScriptBlock{
param($importedFunc);
[ScriptBlock]::Create($importedFunc).Invoke();
} -ArgumentList ${function:checkRegistry}
}
return $result;
}
installPrerequisites;

# Register the user of Windows Update Service if it has not been registered
$MicrosoftUpdateID="7971f918-a847-4430-9279-4a52d1efe18d"
$registered=$MicrosoftUpdateID -in (Get-WUServiceManager).ServiceID
if (!($registered)){
Add-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d -Confirm:$false
}

# Perform Updates
Get-WindowsUpdate -AcceptAll -MicrosoftUpdate -Install -IgnoreReboot;

if (checkPendingReboot){
$warning="There is a pending reboot flag on this host.`n"
$prompt="Please type 'exit' to cancel or 'reboot' to reboot"
$warning;
do{
$userInput=Read-Host -Prompt $prompt;
if ($userInput -match "reboot"){"Restarting command received!";Restart-Computer;} # -match is faster than -like
}while (($userInput -notmatch "reboot") -AND ($userInput -notmatch "(quit|cancel|exit)"))
}else{"Done."}
}
updateLocalWindows;

# Troubleshooting
# Error: Get-WUServiceManager : The 'Get-WUServiceManager' command was found # in the module 'PSWindowsUpdate', but the module
# could not be loaded. For more information, run 'Import-Module PSWindowsUpdate'.
# At line:1 char:1
# + Get-WUServiceManager
# + ~~~~~~~~~~~~~~~~~~~~
# + CategoryInfo : ObjectNotFound: (Get-WUServiceManager:String) # [], CommandNotFoundException
# + FullyQualifiedErrorId : CouldNotAutoloadMatchingModule
#
# Resolution:
# Set-ExecutionPolicy Unrestricted or Bypass
# Step 6: Remediate Common Vulnerabilities
function remediateVulnerabilities{
"`nVCE-2017-829..."
reg add "HKLM\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_PRINT_INFO_DISCLOSURE_FIX" /v iexplore.exe /t REG_DWORD /d 1 /f
reg add "HKLM\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_PRINT_INFO_DISCLOSURE_FIX" /v iexplore.exe /t REG_DWORD /d 1 /f

"`nCVE-2017-5715..."
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management" /v FeatureSettingsOverride /t REG_DWORD /d 0 /f
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management" /v FeatureSettingsOverrideMask /t REG_DWORD /d 3 /f

"`nVCE-2017-5753-54..."
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization" /v MinVmVersionForCpuBasedMitigations /t REG_SZ /d "1.0" /f

"`nASLR Hardening Setting for IE..."
reg add "HKLM\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ALLOW_USER32_EXCEPTION_HANDLER_HARDENING" /v iexplore.exe /t REG_DWORD /d 1 /f
reg add "HKLM\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ALLOW_USER32_EXCEPTION_HANDLER_HARDENING" /v iexplore.exe /t REG_DWORD /d 1 /f

"`nRemediate MS11-025 MFC Remote Code Execution..."
$minVersion=14
$vcVersions=(Get-ItemProperty HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | where {$_.displayname -like "Microsoft Visual C++*"} | Select-Object DisplayVersion)
foreach ($version in $vcVersions){
if($version.DisplayVersion -ge $minVersion){$safeFlag=$True;}
}
if (!($safeFlag)){
try{
New-Item -ItemType Directory -Force -Path C:\Temp
(new-object System.Net.WebClient).DownloadFile('https://download.microsoft.com/download/1/6/5/165255E7-1014-4D0A-B094-B6A430A6BFFC/vcredist_x64.exe','C:\Temp\vcredist_x64.exe')
C:\Temp\vcredist_x64.exe /quiet /norestart
}
catch{
"Unable to download Visual C++"
}
}

"`nSecuring Remote Desktop..."
function secureRDP{
# Remote Desktop Services: Enable NLA Requirement
(Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(1)

# Remote Desktop Services: Require 'High' level of encryption - FIPS compliant
(Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -Filter "TerminalName='RDP-tcp'").SetEncryptionLevel(4)
}
secureRDP;

"`nUpdating Windows Defender..."
try{"`nUpdating Windows Defender Antimalware Virus Definitions...";Update-MPSignature;}
catch{"Cannot update Windows Defender."}

"`nFix Unquoted Service Path Enumerations..."
function fixUnquotedServicePathEnum{
$fixScriptDestination="C:\Temp\Windows_Path_Enumerate.ps1"
$fixScriptDownload="https://gallery.technet.microsoft.com/scriptcenter/Windows-Unquoted-Service-190f0341/file/136821/7/Windows_Path_Enumerate.ps1"
(new-object System.Net.WebClient).DownloadFile($fixScriptDownload, $fixScriptDestination)
C:\Temp\Windows_Path_Enumerate.ps1 -FixUninstall -FixEnv
}
fixUnquotedServicePathEnum;

"`nApplying IIS Crypto Templates..."
function installIISCrypto{
# Download iisCrypto
New-Item -ItemType Directory -Force -Path C:\Temp
$url = "https://kimconnect.com/wp-content/uploads/2019/05/IISCryptoCli.zip"
$temp = "C:\Temp\IISCryptoCli.zip"
(new-object System.Net.WebClient).DownloadFile($url,$temp)

$destination="C:\Windows"
expand-archive -path $temp -destinationpath $destination
}
installIISCrypto;

function applyIISCrypto{
$templateValues="pci32","best","strict","fips140","default"
$count=$templateValues.length
for ($i=0; $i -lt $count; $i++) { $template=$templateValues[$i];"$i`: $template"}
$index=Read-Host -Prompt "Type in the Template Index NUMBER from 0 to $($count-1) to apply"
if ($index -lt $count){
$iisCryptoExist=([System.IO.File]::Exists("C:\Windows\IISCryptoCli.exe"))
if ($iisCryptoExist){
$choice=$templateValues[$index]
"`nBacking up registry into C:\backup.reg, and applying $choice template..."
IISCryptoCli /backup C:\backup.reg /template $choice;
"`nIISCrypto $choice template has been applied...`nPlease reboot machine for changes to take effect."
}
else{
"`nIISCryto wasn't installed. Retrying..."
installIISCripto;
applyIISCrypto;
}
}
else{"Index number was not recognized. Thus, IISCrypto Template was NOT applied."}
}
applyIISCrypto;

# Disable SMB1
Disable-WindowsOptionalFeature -Online -FeatureName smb1protocol -InformationAction SilentlyContinue -NoRestart

}

function enableIcmp{
#IPv4 netsh advfirewall firewall add rule name="ICMP Allow incoming V4 echo request" protocol="icmpv4:8,any" dir=in action=allow #IPv6 netsh advfirewall firewall add rule name="ICMP Allow incoming V6 echo request" protocol="icmpv6:8,any" dir=in action=allow
}

remediateVulnerabilities;
enableIcmp;
restart-computer;

This ‘Step 7’ has been recomposed here.

# Step 7: Optimize & Clean Windows
function optimizeWindows{
"`nSet Power Options..."
function setPowerMax{
powercfg /setactive SCHEME_MIN
powercfg /hibernate off
}
setPowerMax;

"Disable Automatic Startup Repair..."
cmd.exe /c "bcdedit /set {default} recoveryenabled No"
cmd.exe /c "bcdedit /set {default} bootstatuspolicy ignoreallfailures"

$system32="$env:windir\System32"
$annoyingNotifications="$system32\musnotification.exe","$system32\musnotificationux.exe"
$denyExecute= New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone","Execute","Deny")
$annoyingNotifications|%{
#takeown /f $_;
$acl = Get-ACL $_
$acl.AddAccessRule($denyExecute)
Set-Acl $_ $acl
}

}

function removeBloatware{
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$bloatwareRemovalDownload="https://github.com/Sycnex/Windows10Debloater/archive/master.zip"
$bloatwareRemovalDestination="C:\Temp\Windows10Debloater-master.zip"
(New-Object System.Net.WebClient).DownloadFile($bloatwareRemovalDownload, $bloatwareRemovalDestination)
$destination="C:\Temp"
expand-archive -path $bloatwareRemovalDestination -DestinationPath $destination
PowerShell.exe -executionpolicy bypass -File C:\Temp\Windows10Debloater-master\Windows10Debloater.ps1 -Confirm:$False

# Disable Windows Media (a vector of attack surface from malware)
Disable-WindowsOptionalFeature –FeatureName "WindowsMediaPlayer" -Online

# Disable XPS
Disable-WindowsOptionalFeature -Online -FeatureName "Printing-XPSServices-Features"

# Workfolder Client
Disable-WindowsOptionalFeature -Online -FeatureName "WorkFolders-Client"

# Remove Windows Store
Get-AppxPackage -AllUsers | Where-Object {$_.Name -like "Microsoft.WindowsStore*"} | remove-appxpackage
}
removeBloatware;

function cleanWindows{
"Clear Windows Update Cache..."
Dism.exe /online /Cleanup-Image /StartComponentCleanup

"Delete files in Temp directory..."
del C:\Temp\*.* -Recurse -Force

"Prune Event Logs..."
wevtutil el | Foreach-Object {wevtutil cl "$_"}

"Performing Disk Cleanup..."
$HKLM = [UInt32] "0x80000002"
$strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
$strValueName = "StateFlags0065"

$subkeys = gci -Path HKLM:\$strKeyPath -Name
ForEach ($subkey in $subkeys) {
New-ItemProperty -Path HKLM:\$strKeyPath\$subkey -Name $strValueName -PropertyType DWord -Value 2 -ErrorAction SilentlyContinue| Out-Null
Start-Process cleanmgr -ArgumentList "/sagerun:65" -Wait -NoNewWindow -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
}
ForEach ($subkey in $subkeys) {
Remove-ItemProperty -Path HKLM:\$strKeyPath\$subkey -Name $strValueName | Out-Null
}
}
cleanWindows;

Enable/Disable Windows Firewall

function disableFirewall{
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False;
}

function enableFirewall{
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True;
}

disableFirewall;
enableFirewall;

Decrapifier by Spiceworks’ member csand (https://community.spiceworks.com/scripts/show/4378-windows-10-decrapifier-18xx-19xx)

function decrapifyWindows {

    #Windows 10 Decrapifier 18XX/19XX
    #By CSAND
    #April 24 2020
    #
    #
    #PURPOSE: Eliminate much of the bloat that comes with Windows 10. Change many privacy settings to be off by default. Remove built-in advertising, Cortana, OneDrive, Cortana stuff (all optional). Disable some data collection.
    #         Clean up the start menu for new user accounts. Remove a bunch of pre-installed apps, or all of them (including the store). Create a more professional looking W10 experience. Changes some settings no longer
    #         available via GPO for Professional edition.  All of this without breaking Windows.
    #
    #DISCLAIMER: Most of the changes are easily undone, but some like removing the store are difficult to undo.  You should use local/group policy to remove the store if you want.
    #            The -allapps switch is there but I do not recommend most people use it.
    #            I encourage you to research these changes beforehand, and read through the script.
    #            Each section is described with comments, to make it easier to see what's going on.
    #
    #         
    #INSTRUCTIONS: For best results use the following how-tos. Running from an existing profile on an "in-use" machine won't affect any already-existing user profiles and won't give the best results.
    #              Read through the script to see what is disabled, and comment out anything you want to keep. By default a transcript is saved at SYSTEMDRIVE\WindowsDCtranscript.txt.
    #
    #Single machine how-to:
    #https://community.spiceworks.com/how_to/148624-how-to-clean-up-a-single-windows-10-machine-image-using-decrapifier
    #
    #Basic MDT how-to:
    #https://community.spiceworks.com/how_to/150455-shoehorn-decrapifier-into-your-mdt-task
    #
    #
    #Join the Spiceworks Decrapifier community group on Spiceworks! 
    #https://community.spiceworks.com/user-groups/windows-decrapifier-group
    #
    #Common questions/issues:
    #https://community.spiceworks.com/topic/2149611-common-questions-and-problems?page=1#entry-7850320
    #
    #
    #OFFICIAL DOWNLOAD:
    #https://community.spiceworks.com/scripts/show/4378-windows-10-decrapifier-1803
    #This is the only place I post any updates to this script.
    #
    #Changelog:
    #https://community.spiceworks.com/topic/2162951-changelog
    #
    #Previous versions:
    #https://community.spiceworks.com/scripts/show/3977-windows-10-decrapifier-1709
    #https://community.spiceworks.com/scripts/show/3298-windows-10-decrapifier-version-1
    #
    #
    #
    #***Switches***
    # 
    #Switch         Function
    #---------------------------
    #No switches    Disables unnecessary services and scheduled tasks. Removes all UWP apps except for some useful ones. Disables Cortana, OneDrive, restricts default privacy settings and cleans up the default start menu.
    #-AllApps       Removes ALL apps including the store. Make sure this is what you want before you do it. It can be tough to get the store back. Seriously, don't do this unless you are 100% certain.
    #-LeaveTasks    Leaves scheduled tasks alone.
    #-LeaveServices Leaves services alone.
    #-AppAccess     By default this script will restrict almost all the permissions in Settings -> Privacy. This will prevent that from happening.
    #-ClearStart    Empties the start menu completely leaving you with just the apps list.
    #-OneDrive      Leaves OneDrive and Onedrive for Business fully functional.
    #-Tablet        Use this for tablets or 2-in-1s to leave location and sensors enabled.
    #-Cortana       Leave Cortana and web enabled search intact... if that's what you really want.
    #-Xbox          Leave xBox apps and related items.
    #-NoLog         Don't copy transcript to systemdrive\WindowsDCtranscript.txt.
    #-AppsOnly      Only removes apps, doesn't touch privacy settings, services, and scheduled tasks. Cannot be used with -SettingsOnly switch. Can be used with all the others.
    #-SettingsOnly  Only adjusts privacy settings, services, and scheduled tasks. Leaves apps. Cannot be used with -AppsOnly switch.  Can be used with all others (-AllApps won't do anything in that case, obviously).
 
    [cmdletbinding(DefaultParameterSetName = "Decrapifier")]
    param (
        [switch]$AllApps, 
        [switch]$LeaveTasks,
        [switch]$LeaveServices,
        [switch]$AppAccess,
        [switch]$OneDrive,
        [switch]$Xbox,
        [switch]$Tablet,
        [switch]$Cortana,
        [switch]$ClearStart,
        [switch]$NoLog,
        [Parameter(ParameterSetName = "AppsOnly")]
        [switch]$AppsOnly,
        [Parameter(ParameterSetName = "SettingsOnly")]
        [switch]$SettingsOnly
    )
 
    #------USER EDITABLE VARIABLES - change these to your tastes!------
 
    #Apps to keep. Wildcard is implied so try to be specific enough to not overlap with apps you do want removed. 
    #Make sure not begin or end with a "|". ex: "app|app2" - good. "|app|app2|" - bad.
 
    $GoodApps = "calculator|sticky|store|windows.photos|soundrecorder|mspaint|screensketch"
 
    #Start Menu XML. If you run the script without -ClearStart, the XML below will be used for a custom start layout. By default it just leaves File Explorer, classic Control Panel, and Snipping Tool tiles.
    #Place your XML like so:
    #   $StartLayourStr = @"
    #   <**YOUR START LAYOUT XML**>
    #   "@
 
    $StartLayoutStr = @" 
<LayoutModificationTemplate Version="1" xmlns="http://schemas.microsoft.com/Start/2014/LayoutModification">
  <LayoutOptions StartTileGroupCellWidth="6" />
  <DefaultLayoutOverride>
    <StartLayoutCollection>
      <defaultlayout:StartLayout GroupCellWidth="6" xmlns:defaultlayout="http://schemas.microsoft.com/Start/2014/FullDefaultLayout">
        <start:Group Name="" xmlns:start="http://schemas.microsoft.com/Start/2014/StartLayout">
          <start:DesktopApplicationTile Size="2x2" Column="0" Row="0" DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\System Tools\File Explorer.lnk" />
          <start:DesktopApplicationTile Size="2x2" Column="2" Row="0" DesktopApplicationLinkPath="%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\Accessories\Snipping Tool.lnk" />
          <start:DesktopApplicationTile Size="2x2" Column="0" Row="2" DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\System Tools\Control Panel.lnk" />
        </start:Group>
      </defaultlayout:StartLayout>
    </StartLayoutCollection>
  </DefaultLayoutOverride>
</LayoutModificationTemplate>
"@
 
    #------End editable variables------
 
 
    #---Functions---
 
    #Appx removal
    #Removes all apps or some apps depending on switches used.
 
    Function RemoveApps {
        #SafeApps contains apps that shouldn't be removed, or just can't and cause errors
        $SafeApps = "AAD.brokerplugin|accountscontrol|apprep.chxapp|assignedaccess|asynctext|bioenrollment|capturepicker|cloudexperience|contentdelivery|desktopappinstaller|ecapp|getstarted|immersivecontrolpanel|lockapp|net.native|oobenet|parentalcontrols|PPIProjection|sechealth|secureas|shellexperience|startmenuexperience|vclibs|xaml|XGpuEject"
        If ($Xbox) {
            $SafeApps = "$SafeApps|Xbox"
        }
     
        If ($Allapps) {
            $RemoveApps = Get-AppxPackage -allusers | where-object { $_.name -notmatch $SafeApps }
            $RemovePrApps = Get-AppxProvisionedPackage -online | where-object { $_.displayname -notmatch $SafeApps }
            ForEach ($RemovedApp in $RemoveApps) {
                Write-Host Removing app package: $RemovedApp.name
                Remove-AppxPackage -package $RemovedApp -erroraction silentlycontinue
                 
            }           ForEach ($RemovedPrApp in $RemovePrApps) {
                Write-Host Removing provisioned app $RemovedPrApp.displayname
                Remove-AppxProvisionedPackage -online -packagename $RemovedPrApp.packagename -erroraction silentlycontinue
                 
            }
        }
        Else {
            $SafeApps = "$SafeApps|$GoodApps"
            $RemoveApps = Get-AppxPackage -allusers | where-object { $_.name -notmatch $SafeApps }
            $RemovePrApps = Get-AppxProvisionedPackage -online | where-object { $_.displayname -notmatch $SafeApps }
            ForEach ($RemovedApp in $RemoveApps) {
                Write-Host Removing app package: $RemovedApp.name
                Remove-AppxPackage -package $RemovedApp -erroraction silentlycontinue
                 
            }           ForEach ($RemovedPrApp in $RemovePrApps) {
                Write-Host Removing provisioned app $RemovedPrApp.displayname
                Remove-AppxProvisionedPackage -online -packagename $RemovedPrApp.packagename -erroraction silentlycontinue
                 
            }
        }
    } 
    #End Function RemoveApps
         
     
    #Disable scheduled tasks
    #Tasks: Various CEIP and information gathering/sending tasks.
    Function DisableTasks {
        If ($LeaveTasks) {
            Write-Host "***Leavetasks switch set - leaving scheduled tasks alone...***"
        }
        Else {
            Write-Host "***Disabling some unecessary scheduled tasks...***"
            Get-Scheduledtask "Microsoft Compatibility Appraiser", "ProgramDataUpdater", "Consolidator", "KernelCeipTask", "UsbCeip", "Microsoft-Windows-DiskDiagnosticDataCollector", "GatherNetworkInfo", "QueueReporting" -erroraction silentlycontinue | Disable-scheduledtask
        }
    }
 
 
    #Disable services
    Function DisableServices {
        If ($LeaveServices) {
            Write-Host "***Leaveservices switch set - leaving services alone...***"
        }
        Else {
            Write-Host "***Stopping and disabling some services...***"
            #Diagnostics tracking WMP Network Sharing
            Get-Service Diagtrack, WMPNetworkSvc -erroraction silentlycontinue | stop-service -passthru | set-service -startuptype disabled
            #WAP Push Message Routing  NOTE Sysprep w/ Generalize WILL FAIL if you disable the DmwApPushService. Commented out by default.
            #Get-Service DmwApPushService -erroraction silentlycontinue | stop-service -passthru | set-service -startuptype disabled
            #Disable OneSync service - Used to sync various apps and settings if you enable that (contacts, etc). Commented out by default to not break functionality.
            #Get-Service OneSyncSvc | stop-service -passthru | set-service -startuptype disabled
         
            #xBox services
            If ($Xbox) {
            }
            Else {
                #Disable xBox services - "xBox Game Monitoring Service" - XBGM - Can't be disabled (access denied)
                Get-Service XblAuthManager, XblGameSave, XboxNetApiSvc -erroraction silentlycontinue | stop-service -passthru | set-service -startuptype disabled
            }       
        }
    }
 
         
    #Registry change functions
    #Load default user hive
    Function loaddefaulthive {
        $matjazp72 = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' Default).Default
        reg load "$reglocation" $matjazp72\ntuser.dat
    }
 
 
    #Unload default user hive
    Function unloaddefaulthive {
        [gc]::collect()
        reg unload "$reglocation"
    }
 
 
    #Cycle registry locations - 1st pass HKCU, 2nd pass default NTUSER.dat
    Function RegChange {
        Write-Host "***Applying registry items to HKCU...***"
        $reglocation = "HKCU"
        regsetuser
        $reglocation = "HKLM\AllProfile"
        Write-Host "***Applying registry items to default NTUSER.DAT...***"
        loaddefaulthive; regsetuser; unloaddefaulthive
        $reglocation = $null
        Write-Host "***Applying registry items to HKLM...***"
        regsetmachine
        Write-Host "***Registry set current user and default user, and policies set for local machine!***"
    }
 
 
    #Set current and default user registry settings
    Function RegSetUser {
        #Start menu suggestions
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SystemPaneSuggestionsEnabled" /D 0 /F
        #Show suggested content in settings
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SubscribedContent-338393Enabled" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SubscribedContent-353694Enabled" /D 0 /F
        #Show suggestions occasionally
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SubscribedContent-338388Enabled" /D 0 /F
        #Multitasking - Show suggestions in timeline
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SubscribedContent-353698Enabled" /D 0 /F
        #Lockscreen suggestions, rotating pictures
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SoftLandingEnabled" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "RotatingLockScreenEnabled" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "RotatingLockScreenOverlayEnabled" /D 0 /F
        #Preinstalled apps, Minecraft Twitter etc all that - still need a clean default start menu to fully eliminate
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "PreInstalledAppsEnabled" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "PreInstalledAppsEverEnabled" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "OEMPreInstalledAppsEnabled" /D 0 /F
        #MS shoehorning apps quietly into your profile
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SilentInstalledAppsEnabled" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "ContentDeliveryAllowed" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SubscribedContentEnabled" /D 0 /F
        #Ads in File Explorer
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" /T REG_DWORD /V "ShowSyncProviderNotifications" /D 0 /F
        #Show me the Windows welcome experience after updates and occasionally
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SubscribedContent-310093Enabled" /D 0 /F
        #Get tips, tricks, suggestions as you use Windows 
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SubscribedContent-338389Enabled" /D 0 /F
 
        #Privacy Settings
        #Let websites provide local content by accessing language list - appears to reset during OOBE.
        #Reg Add "$reglocation\Control Panel\International\User Profile" /T REG_DWORD /V "HttpAcceptLanguageOptOut" /D 1 /F
        #Ask for feedback
        Reg Add "$reglocation\SOFTWARE\Microsoft\Siuf\Rules" /T REG_DWORD /V "NumberOfSIUFInPeriod" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\Siuf\Rules" /T REG_DWORD /V "PeriodInNanoSeconds" /D 0 /F
        #Let apps use advertising ID
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo" /T REG_DWORD /V "Enabled" /D 0 /F
        #Let Windows track app launches to improve start and search results - includes run history
        #Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" /T REG_DWORD /V "Start_TrackProgs" /D 0 /F
        #Tailored experiences - Diagnostics & Feedback settings
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Privacy" /T REG_DWORD /V "TailoredExperiencesWithDiagnosticDataEnabled" /D 0 /F
        #Let apps on other devices open messages and apps on this device - Shared Experiences settings
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CDP" /T REG_DWORD /V "RomeSdkChannelUserAuthzPolicy" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CDP" /T REG_DWORD /V "CdpSessionUserAuthzPolicy" /D 0 /F
     
        #Speech Inking & Typing - comment out if you use the pen\stylus a lot
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\SettingSync\Groups\Language" /T REG_DWORD /V "Enabled" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\InputPersonalization" /T REG_DWORD /V "RestrictImplicitTextCollection" /D 1 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\InputPersonalization" /T REG_DWORD /V "RestrictImplicitInkCollection" /D 1 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\InputPersonalization\TrainedDataStore" /T REG_DWORD /V "HarvestContacts" /D 0 /F
        Reg Add "$reglocation\SOFTWARE\Microsoft\Personalization\Settings" /T REG_DWORD /V "AcceptedPrivacyPolicy" /D 0 /F
        #Improve inking & typing recognition
        Reg Add "$reglocation\SOFTWARE\Microsoft\Input\TIPC" /T REG_DWORD /V "Enabled" /D 0 /F
        #Pen & Windows Ink - Show recommended app suggestions
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\PenWorkspace" /T REG_DWORD /V "PenWorkspaceAppSuggestionsEnabled" /D 0 /F
     
        #People
        #Show My People notifications
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People\ShoulderTap" /T REG_DWORD /V "ShoulderTap" /D 0 /F
        #Show My People app suggestions
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /T REG_DWORD /V "SubscribedContent-314563Enabled" /D 0 /F
        #People on Taskbar
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People" /T REG_DWORD /V "PeopleBand" /D 0 /F
     
        #Other Settings
        #Use Autoplay for all media and devices
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers" /T REG_DWORD /V "DisableAutoplay" /D 1 /F
        #Taskbar search, personal preference. 0 = no search, 1 = search icon, 2 = search bar
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" /T REG_DWORD /V "SearchboxTaskbarMode" /D 0 /F
        #Allow search to use location if it's enabled
        Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" /T REG_DWORD /V "AllowSearchToUseLocation" /D 0 /F
        #Do not track - Edge
        Reg Add "$reglocation\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer\Storage\microsoft.microsoftedge_8wekyb3d8bbwe\MicrosoftEdge\Main" /T REG_DWORD /V "DoNotTrack" /D 1 /F
        #Do not track - IE
        Reg Add "$reglocation\SOFTWARE\Microsoft\Internet Explorer\Main" /T REG_DWORD /V "DoNotTrack" /D 1 /F
     
        #--Optional User Settings--
     
        #App permissions user settings, these are all available from the settings menu
        If ($AppAccess) {
        }
        Else {  
            #App permissions
            #Location - see tablet settings
            #Camera
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\webcam" /T REG_SZ /V "Value" /D Deny /F
            #Microphone
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\microphone" /T REG_SZ /V "Value" /D Deny /F
            #Notifications - doesn't appear to work in 1803, setting hasn't been moved as of 1803 like most of the others
            #Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{52079E78-A92B-413F-B213-E8FE35712E72}" /T REG_SZ /V "Value" /D Deny /F
            #Account Info
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\userAccountInformation" /T REG_SZ /V "Value" /D Deny /F
            #Contacts
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\contacts" /T REG_SZ /V "Value" /D Deny /F  
            #Calendar
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\appointments" /T REG_SZ /V "Value" /D Deny /F
            #Call history
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\phoneCallHistory" /T REG_SZ /V "Value" /D Deny /F
            #Email
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\email" /T REG_SZ /V "Value" /D Deny /F
            #Tasks
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\userDataTasks" /T REG_SZ /V "Value" /D Deny /F
            #TXT/MMS
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\chat" /T REG_SZ /V "Value" /D Deny /F
            #Radios - doesn't appear to work in 1803, setting hasn't been moved as of 1803 like most of the others
            #Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{A8804298-2D5F-42E3-9531-9C8C39EB29CE}" /T REG_SZ /V "Value" /D Deny /F
            #Other Devices - reset during OOBE
            #Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\LooselyCoupled" /T REG_SZ /V "Value" /D Deny /F
            #Cellular Data
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\cellularData" /T REG_SZ /V "Value" /D Deny /F
            #Allow apps to run in background global setting - seems to reset during OOBE
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications" /T REG_DWORD /V "GlobalUserDisabled" /D 1 /F
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" /T REG_DWORD /V "BackgroundAppGlobalToggle" /D 0 /F 
            #App Diagnostics - doesn't appear to work in 1803, setting hasn't been moved as of 1803 like most of the others
            #Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{2297E4E2-5DBE-466D-A12B-0F8286F0D9CA}" /T REG_SZ /V "Value" /D Deny /F
            #My Documents
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\documentsLibrary" /T REG_SZ /V "Value" /D Deny /F
            #My Pictures
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\picturesLibrary" /T REG_SZ /V "Value" /D Deny /F
            #My Videos
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\videosLibrary" /T REG_SZ /V "Value" /D Deny /F
            #File System
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\broadFileSystemAccess" /T REG_SZ /V "Value" /D Deny /F
         
            #Tablet Settings - use -Tablet switch to leave these on
            If ($Tablet) {
            }
            Else {
                #Deny access to location and sensors
                Reg Add "$reglocation\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Sensor\Permissions\{BFA794E4-F964-4FDB-90F6-51056BFE4B44}" /T REG_DWORD /V "SensorPermissionState" /D 0 /F
                Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{BFA794E4-F964-4FDB-90F6-51056BFE4B44}" /T REG_SZ /V "Value" /D Deny /F
                Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{E6AD100E-5F4E-44CD-BE0F-2265D88D14F5}" /T REG_SZ /V "Value" /D Deny /F
                Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location" /T REG_SZ /V "Value" /D Deny /F
            }
         
        }
     
        #Disable Cortana - use -Cortana to leave it on
        If ($Cortana) {
        }
        Else {
            #Disable Cortana and Bing search user settings
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" /T REG_DWORD /V "CortanaEnabled" /D 0 /F
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" /T REG_DWORD /V "CanCortanaBeEnabled" /D 0 /F
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" /T REG_DWORD /V "DeviceHistoryEnabled" /D 0 /F
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" /T REG_DWORD /V "CortanaConsent" /D 0 /F
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" /T REG_DWORD /V "CortanaInAmbientMode" /D 0 /F
            #Disable Bing search from start menu/search bar
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" /T REG_DWORD /V "BingSearchEnabled" /D 0 /F
            #Disable Cortana on lock screen
            Reg Add "$reglocation\SOFTWARE\Microsoft\Speech_OneCore\Preferences" /T REG_DWORD /V "VoiceActivationEnableAboveLockscreen" /D 0 /F
            #Disable Cortana search history
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" /T REG_DWORD /V "HistoryViewEnabled" /D 0 /F
        }
         
        #Game settings - use -Xbox to leave these on
        If ($Xbox) {
        }
        Else {
            #Disable Game DVR
            Reg Add "$reglocation\System\GameConfigStore" /T REG_DWORD /V "GameDVR_Enabled" /D 0 /F
        }
     
        #OneDrive settings - use -OneDrive switch to leave these on
        If ($OneDrive) {
        }
        Else {
            #Disable OneDrive startup run user settings
            Reg Add "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run" /T REG_BINARY /V "OneDrive" /D 0300000021B9DEB396D7D001 /F
            #Disable automatic OneDrive desktop setup for new accounts
            If ($reglocation -ne "HKCU") {
                Reg Delete "$reglocation\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /V "OneDriveSetup" /F
            }
        }
 
        #End user registry settings
    }
 
 
    #Set local machine settings and local group policies    
    Function RegSetMachine {
        #--Local GP settings--   CONVERT THESE TO HKCU / DEFAULT / HKLM WHERE POSSIBLE
        #Can be adjusted in GPedit.msc in Pro+ editions.
        #Local Policy\Computer Config\Admin Templates\Windows Components            
        #/Application Compatibility
        #Turn off Application Telemetry         
        Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\AppCompat" /T REG_DWORD /V "AITEnable" /D 0 /F            
        #Turn off inventory collector           
        Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\AppCompat" /T REG_DWORD /V "DisableInventory" /D 1 /F
 
        #/Cloud Content         
        #Turn off Consumer Experiences  - Enterprise only (for Pro, HKCU settings and start menu cleanup achieve same result)       
        Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent" /T REG_DWORD /V "DisableWindowsConsumerFeatures" /D 1 /F
        #Turn off all spotlight features    
        #Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\CloudContent" /T REG_DWORD /V "DisableWindowsSpotlightFeatures" /D 1 /F  
 
        #/Data Collection and Preview Builds            
        #Set Telemetry to off (switches to 1:basic for W10Pro and lower)            
        Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection" /T REG_DWORD /V "AllowTelemetry" /D 0 /F
        #Disable pre-release features and settings          
        #Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\PreviewBuilds" /T REG_DWORD /V "EnableConfigFlighting" /D 0 /F
        #Do not show feedback notifications         
        Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection" /T REG_DWORD /V "DoNotShowFeedbackNotifications" /D 1 /F
 
        #/Store
        #Disable all apps from store, commented out by default as it will break the store           
        #Reg Add "HKLM\SOFTWARE\Policies\Microsoft\WindowsStore" /T REG_DWORD /V "DisableStoreApps" /D 1 /F     
        #Turn off Store, left disabled by default           
        #Reg Add "HKLM\SOFTWARE\Policies\Microsoft\WindowsStore" /T REG_DWORD /V "RemoveWindowsStore" /D 1 /F
 
        #/Sync your settings - commented out by default to keep functionality of sync service       
        #Do not sync (anything)         
        #Reg Add    "HKLM\SOFTWARE\Policies\Microsoft\Windows\SettingSync" /T REG_DWORD /V "DisableSettingSync" /D 2 /F
        #Disallow users to override this
        #Reg Add    "HKLM\SOFTWARE\Policies\Microsoft\Windows\SettingSync" /T REG_DWORD /V "DisableSettingSyncUserOverride" /D 1 /F
     
        #Add "Run as different user" to context menu
        Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\Explorer" /T REG_DWORD /V "ShowRunasDifferentuserinStart" /D 1 /F
     
        #!!!None of these effective anymore in 1803!!! Now handled by HKCU settings
        #Disallow web search from desktop search            
        #Reg Add    "HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search" /T REG_DWORD /V "DisableWebSearch" /D 1 /F
        #Don't search the web or display web results in search          
        #Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search" /T REG_DWORD /V "ConnectedSearchUseWeb" /D 0 /F
        #Don't allow search to use location
        #Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search" /T REG_DWORD /V "AllowSearchToUseLocation" /D 0 /F
 
        #/Windows Update            
        #Turn off featured SOFTWARE notifications through Windows Update
        Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" /T REG_DWORD /V "EnableFeaturedSoftware" /D 0 /F
 
        #--Non Local GP Settings--      
        #Delivery Optimization settings - sets to 1 for LAN only, change to 0 for off
        Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config" /T REG_DWORD /V "DownloadMode" /D 1 /F
        Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config" /T REG_DWORD /V "DODownloadMode" /D 1 /F
        Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Settings" /T REG_DWORD /V "DownloadMode" /D 1 /F
     
        #Disabling advertising info and device metadata collection for this machine
        Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo" /T REG_DWORD /V "Enabled" /D 0 /F
        Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Device Metadata" /V "PreventDeviceMetadataFromNetwork" /T REG_DWORD /D 1 /F
 
        #Disable CEIP. GP setting at: Computer Config\Admin Templates\System\Internet Communication Managemen\Internet Communication settings
        Reg Add "HKLM\SOFTWARE\Microsoft\SQMClient\Windows" /T REG_DWORD /V "CEIPEnable" /D 0 /F
     
        #Turn off automatic download/install of store app updates   
        #Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsStore\WindowsUpdate" /T REG_DWORD /V "AutoDownload" /D 2 /F 
     
        #Prevent using sign-in info to automatically finish setting up after an update
        Reg Add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /T REG_DWORD /V "ARSOUserConsent" /D 0 /F
     
        #Prevent apps on other devices from opening apps on this one - disables phone pairing
        #Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\SmartGlass" /T REG_DWORD /V "UserAuthPolicy" /D 0 /F
     
        #Enable diagnostic data viewer
        Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack\EventTranscriptKey" /T REG_DWORD /V "EnableEventTranscript" /D 1 /F
     
        #Disable Edge desktop shortcut
        Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer" /T REG_DWORD /V "DisableEdgeDesktopShortcutCreation" /D 1 /F
     
        #Filter web content through smartscreen. Left enabled by default.
        #Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost" /T REG_DWORD /V "EnableWebContentEvaluation" /D 0 /F
 
        #--Optional Machine Settings--
     
        #Disable Cortana - use -Cortana to leave it on
        If ($Cortana) {
        }
        Else {
            #Cortana local GP - Computer Config\Admin Templates\Windows Components\Search           
            #Disallow Cortana           
            Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search" /T REG_DWORD /V "AllowCortana" /D 0 /F
            #Disallow Cortana on lock screen - seems pointless with above setting, may be deprecated, covered by HKCU anyways       
            #Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\Windows Search" /T REG_DWORD /V "AllowCortanaAboveLock" /D 0 /F
        }
 
        #Tablet Settings - use -Tablet switch to leave these on
        If ($Tablet) {
        }
        Else {
            #Turn off location - global
            Reg Add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location" /T REG_SZ /V "Value" /D Deny /F
        }
     
        #Game settings - use -Xbox to leave these on
        If ($Xbox) {
        }
        Else {
            #Disable Game Monitoring Service
            Reg Add "HKLM\SYSTEM\CurrentControlSet\Services\xbgm" /T REG_DWORD /V "Start" /D 4 /F
            #GameDVR local GP - Computer Config\Admin Templates\Windows Components\Windows Game Recording and Broadcasting
            Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\GameDVR" /T REG_DWORD /V "AllowGameDVR" /D 0 /F
        }
 
        #OneDrive settings - use -OneDrive switch to leave these on
        If ($OneDrive) {
        }
        Else {
            #Prevent usage of OneDrive local GP - Computer Config\Admin Templates\Windows Components\OneDrive   
            Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\OneDrive" /T REG_DWORD /V "DisableFileSyncNGSC" /D 1 /F
            Reg Add "HKLM\SOFTWARE\Policies\Microsoft\Windows\OneDrive" /T REG_DWORD /V "DisableFileSync" /D 1 /F
            #Remove OneDrive from File Explorer
            Reg Add "HKCR\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}" /T REG_DWORD /V "System.IsPinnedToNameSpaceTree" /D 0 /F
            Reg Add "HKCR\Wow6432Node\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}" /T REG_DWORD /V "System.IsPinnedToNameSpaceTree" /D 0 /F
        }
     
        #End machine registry settings
    }           
 
 
    #Clean up the default start menu    
    Function ClearStartMenu {
        If ($ClearStart) {
            Write-Host "***Setting empty start menu for new profiles...***"
            #Don't edit this. Creates empty start menu if -ClearStart is used.
            $StartLayoutStr = @"
<LayoutModificationTemplate Version="1" xmlns="http://schemas.microsoft.com/Start/2014/LayoutModification" xmlns:defaultlayout="http://schemas.microsoft.com/Start/2014/FullDefaultLayout" xmlns:start="http://schemas.microsoft.com/Start/2014/StartLayout" xmlns:taskbar="http://schemas.microsoft.com/Start/2014/TaskbarLayout">
  <LayoutOptions StartTileGroupCellWidth="6" />
  <DefaultLayoutOverride>
    <StartLayoutCollection>
      <defaultlayout:StartLayout GroupCellWidth="6" xmlns:defaultlayout="http://schemas.microsoft.com/Start/2014/FullDefaultLayout">
      </defaultlayout:StartLayout>
    </StartLayoutCollection>
  </DefaultLayoutOverride>
  </LayoutModificationTemplate>
"@
            add-content $Env:TEMP\startlayout.xml $StartLayoutStr
            import-startlayout -layoutpath $Env:TEMP\startlayout.xml -mountpath $Env:SYSTEMDRIVE\
            remove-item $Env:TEMP\startlayout.xml
        }
        Else {        
            Write-Host "***Setting clean start menu for new profiles...***"
            #Custom start layout XML near the top of the script.
 
            add-content $Env:TEMP\startlayout.xml $StartLayoutStr
            import-startlayout -layoutpath $Env:TEMP\startlayout.xml -mountpath $Env:SYSTEMDRIVE\
            remove-item $Env:TEMP\startlayout.xml
        }
    }
 
 
    #Goodbye Message Function
    Function Goodbye {
        Write-Host "*******Decrapification complete.*******"
        Write-Host "*******Remember to set your execution policy back!  Set-Executionpolicy restricted is the Windows 10 default.*******"
        Write-Host "*******Reboot your computer now!*******"    
    }
 
    #---End of functions---
 
 
    #Decrapify
    If ($NoLog) {
    }
    Else {
        Start-Transcript $ENV:SYSTEMDRIVE\WindowsDCtranscript.txt
    }
    Write-Host "******Decrapifying Windows 10...******"
    If ($AppsOnly) {
        RemoveApps
        ClearStartMenu
        Goodbye
    }
    Elseif ($SettingsOnly) {
        DisableTasks
        DisableServices
        RegChange
        ClearStartMenu
        Goodbye
    }
    Else {
        RemoveApps
        DisableTasks
        DisableServices
        RegChange
        ClearStartMenu
        Goodbye
    }
 
    If ($NoLog) {
    }
    Else {
        Stop-Transcript
    }
}

decrapifyWindows -AllApps -NoLog -ClearStart

Leave a Reply

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