Why stateless device, stateless OS?

OS might be buggy

Now Windows 11 is very buggy. Stuck everyday. Unresponsive everyday. Store stop working every day.

Since those tiny problems emerge endlessly on Windows 11. Often inexplicable systems will fall into weird failures. Solving these problems is very difficult, and it may require us to understand how Windows works.

However, reinstalling Windows is very easy. And following the best practice of how we use Windows in datacenter, Windows needs to be reimaged at least once a month.

Device isn't responsible for saving data

Today, all our data, codes, and information are stored in the cloud. In contrast, our equipment is more like some computing resources. When we buy a computer, what we buy is just an instrument that can use cloud services. Our hard disk is just a layer of cache for cloud resources.

This is a brand new usage concept: when we use devices and operating systems, we should not rely on the devices and operating systems themselves. At any time, our equipment and operating system are lost or damaged, and we only need to reset them to restore access.

I call it: stateless hardware, stateless system.

Pain point

However, resetting may not be easy. You need to spend 10 minutes to download the image, 10 minutes to install, 10 minutes to complete the initial setup, and about 3 hours to configure it as a working state that you can use.

> Reference: Install Windows 11 side-by-side without a USB drive - Anduin Xue (aiursoft.com)

If we can automate the system configuration, then we won't have to wait for those 3 hours.

This blog will briefly introduce my experience in building automated configuration scripts.

Automation Windows configuration

You need to build your own automation script. I strongly suggest to put it on GitHub or OneDrive.

For example, my automation script is here: My Windows Configuration script | configuration-script-win (aiurs.co)

You can also directly fork that repo and modify those scripts to your own.

Tips for PowerShell automation:

Get if current shell has admin privilege:
function Get-IsElevated {
    $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $p = New-Object System.Security.Principal.WindowsPrincipal($id)
    if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
    { Write-Output $true }      
    else
    { Write-Output $false }   
}

if (-not(Get-IsElevated)) { 
    throw "Please run this script as an administrator" 
}
Re-install Windows:

The next function needs to be run with Administrator priviledge.

It will provide you options for downloading the Windows installer ISO. You can download it via any tool you like, and tell the script the file location.

Also, you need to prepare a clean drive, (Example: D:) as the disk storage for Windows to be installed.

function Get-IsElevated {
    $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $p = New-Object System.Security.Principal.WindowsPrincipal($id)
    if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
    { Write-Output $true }      
    else
    { Write-Output $false }   
}

    
function Reimage {
    if (-not(Get-IsElevated)) { 
        throw "Please run this script as an administrator" 
    }

    # Get a drive, get the WIM file.
    $systemDrive = (Get-WmiObject Win32_OperatingSystem).SystemDrive.Trim(':')
    # Get disk
    Write-Host "Please provide me a clean disk amount point. Example: 'Q': " -ForegroundColor Yellow
    $diskMount = $(Read-Host).Trim(':')

    # Ensure disk exists
    if (Test-Path -Path "$($diskMount):\") {
        Write-Host "Disk $diskMount exists!" -ForegroundColor Green
    } else {
        throw "Disk $diskMount doesn't exist!"
    }

    if ($systemDrive.ToLower() -eq $diskMount.ToLower()) {
        throw "You can't install new OS on your existing OS drive: $diskMount!"
    }

    # Ensure disk enough size
    if ((Get-Volume $diskMount).Size -lt 50000000000) {
        throw "Disk $diskMount too mall! Please assign at least 50GB!"
    }

    # Format to NTFS.
    Get-ChildItem "$($diskMount):\" -ErrorAction SilentlyContinue
    Write-Host "Enter 'Y' if you want to format disk $diskMount [Y or N]:" -ForegroundColor Yellow
    $format = Read-Host
    if ($format -eq "Y") {
        Format-Volume -DriveLetter $diskMount -FileSystem NTFS 
    } else {
        throw "You must format that disk first!"
    }

    # Disable Bitlocker
    Disable-BitLocker -MountPoint $diskMount
    
    do {
        Write-Host "We need the Windows image file. What do you have now?`n" -ForegroundColor Yellow
        Write-Host -NoNewline "A: " -ForegroundColor White
        Write-Host "I have nothing. Help me download the new OS."
        Write-Host -NoNewline "B: " -ForegroundColor White
        Write-Host "I have nothing. Tell me how to download the new OS. (I will manually download it)"
        Write-Host -NoNewline "C: " -ForegroundColor White
        Write-Host "I already have the ISO file downloaded locally."
        Write-Host -NoNewline "D: " -ForegroundColor White
        Write-Host "I already have the install.wim file locally.`n"

        $userOption = Read-Host -Prompt 'Select'
        if($userOption.Length -eq 1 -and $userOption.ToLower() -ge "a" -and $userOption.ToLower() -le "d") {
            break
        } else {
            Write-Host "Invalid input!" -ForegroundColor Red
        }
    } until($false)

    if ($userOption.ToLower() -eq "a") {
        Start-Process powershell {
            Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://githubcontent.aiurs.co/pbatard/Fido/master/Fido.ps1'))
        }

        Read-Host "Press [Enter] if you finished downloading the ISO file."
    } 
    
    if ($userOption.ToLower() -eq "b") {
        Write-Host "Please open the following link to download Windows ISO:`n" -ForegroundColor Yellow
        Write-Host -NoNewline "Download Windows 10: " -ForegroundColor White
        Write-Host "https://www.microsoft.com/en-US/software-download/windows10" -ForegroundColor DarkBlue
        Write-Host -NoNewline "Download Windows 11: " -ForegroundColor White
        Write-Host "https://www.microsoft.com/en-us/software-download/windows11" -ForegroundColor DarkBlue
        Write-Host -NoNewline "Download Windows Insider: " -ForegroundColor White
        Write-Host "Download Windows Insider: https://www.microsoft.com/en-us/software-download/windowsinsiderpreviewiso" -ForegroundColor DarkBlue
        
        Read-Host "Press [Enter] if you finished downloading the ISO file."
    }

    if ($userOption.ToLower() -eq "a" -or $userOption.ToLower() -eq "b" -or $userOption.ToLower() -eq "c") {
        # Enlist ISO options
        Write-Host "All ISO files here ($($(Get-Location))): " -ForegroundColor White
        Get-ChildItem -Filter "*.iso" | Format-Table -AutoSize

        Write-Host "`nPlease provide me the path of your ISO file (ends with .iso):" -ForegroundColor Yellow

        $iso = Read-Host
        $iso = (Resolve-Path $iso).Path
        if (Test-Path -Path "$iso") {
            Get-Item "$iso" | Format-List
            Write-Host "ISO $iso exists!" -ForegroundColor Green
        } else {
            throw "ISO $iso doesn't exist! Please check your path!"
        }

        # Mount ISO
        $mounted = Mount-DiskImage -ImagePath $iso -Access ReadOnly -StorageType ISO
        $mountedISO = Get-Volume -DiskImage $mounted
        Write-Host "Mounted:" -ForegroundColor Green
        $mountedISO | Format-List
        $mountedLetter = $mountedISO.DriveLetter
        Write-Host "Files inside:" -ForegroundColor Green
        Get-ChildItem "$($mountedLetter):" | Format-Table -AutoSize

        # Get OS Index
        $wimFile = "$($mountedLetter):\sources\install.wim"
    }

    if ($userOption.ToLower() -eq "d") {
        # Enlist ISO options
        Write-Host "All WIM files here ($($(Get-Location))): " -ForegroundColor White
        Get-ChildItem -Filter "*.wim" | Format-Table -AutoSize

        Write-Host "`nPlease provide me the path of your WIM file:" -ForegroundColor Yellow

        $wim = Read-Host
        $wim = (Resolve-Path $wim).Path
        if (Test-Path -Path "$wim") {
            Get-Item "$wim" | Format-List
            Write-Host "WIM $wim exists!" -ForegroundColor Green
        } else {
            throw "WIM $wim doesn't exist!"
        }

        $wimFile = $wim
    }

    dism /Get-ImageInfo /imagefile:"$wimFile"
    Write-Host "Please provide the OS Index number. Example: '6': " -ForegroundColor Yellow
    $osIndex = Read-Host

    # Get OS Name
    Write-Host "Please name the new OS. Example: Windows VNext: " -ForegroundColor Yellow
    $osName = Read-Host

    Write-Host "Extracting OS..." -ForegroundColor Green
    dism /apply-image /imagefile:"$wimFile" /index:"$osIndex" /ApplyDir:"$($diskMount):\"

    # Dismount ISO
    if ($iso) {
        Write-Host "Dismounting the iso..." -ForegroundColor Green
        Dismount-DiskImage $iso -ErrorAction SilentlyContinue
    }

    # Create start up registry.
    $created = bcdedit /create /d "$osName" /application osloader
    $osID = $created | Select-String -Pattern '{[-0-9A-F]+?}' -AllMatches | Select-Object -ExpandProperty Matches | Select-Object -ExpandProperty Value
    bcdedit /set "$osID" device "partition=$($diskMount):"
    bcdedit /set "$osID" path "\WINDOWS\system32\winload.efi"
    bcdedit /set "$osID" systemroot "\WINDOWS"
    bcdedit /set "$osID" osdevice "partition=$($diskMount):"
    bcdedit /set "$osID" locale "en-US"
    bcdedit /set "$osID" inherit "{bootloadersettings}"
    bcdedit /set "$osID" nx "OptIn"
    bcdedit /set "$osID" bootmenupolicy "Standard"
    bcdedit /set "$osID" displaymessageoverride "Recovery"
    bcdedit /set "$osID" recoveryenabled "Yes"
    bcdedit /set "$osID" isolatedcontext "Yes"
    bcdedit /set "$osID" flightsigning "Yes"
    bcdedit /set "$osID" allowedinmemorysettings "0x15000075"
    bcdedit /displayorder "$osID" /addlast
    bcdedit /set "{bootmgr}" default "$osID"
    Write-Host "Modified boot configuration:" -ForegroundColor Green
    bcdedit

    # Disable Bitlocker
    Disable-BitLocker -MountPoint $diskMount
    
    Write-Host "Unmounting hard disk..." -ForegroundColor Green
    mountvol "$($diskMount):" /P

    Write-Host "Job finished! Pending reboot!" -ForegroundColor Green
    Write-Host "Press Enter to reboot now..." -ForegroundColor Yellow
    Read-Host
    
    Restart-Computer -Force
}
Get current AAD user details:
if (-not $(Get-Command Connect-AzureAD -ErrorAction SilentlyContinue)) {
    # Install Nuget provider.
    Write-Host "Installing Nuget PowerShell Package Provider..." -ForegroundColor Green
    Install-PackageProvider -Name NuGet -Force

    # Install Azure AD Module
    Write-Host "Installing AzureAD PowerShell module..." -ForegroundColor Green
    Install-Module AzureAD -Force
} else {
    Write-Host "Azure AD PowerShell Module is already installed!" -ForegroundColor Green
}

# Request Azure Details.
$aad = Connect-AzureAD
$email = $aad.Account.Id
$name = (Get-AzureADUser -ObjectId $email).DisplayName
Get system drive letter:
$driveLetter = (Get-Location).Drive.Name
Ask the user to rename the OS:
$computerName = Read-Host "Enter New Computer Name if you want to rename it: ($($env:COMPUTERNAME))"
if (-not ([string]::IsNullOrEmpty($computerName)))
{
    Write-Host "Renaming computer to $computerName..." -ForegroundColor Green
    cmd /c "bcdedit /set {current} description `"$computerName`""
    Rename-Computer -NewName $computerName
}
Install Winget
# Install Winget
if (-not $(Get-Command winget -ErrorAction SilentlyContinue)) {
    Write-Host "Installing WinGet..." -ForegroundColor Green
    Start-Process "ms-appinstaller:?source=https://aka.ms/getwinget"
    while(-not $(Get-Command winget -ErrorAction SilentlyContinue))
    {
        Write-Host "Winget is still not found!" -ForegroundColor Yellow
        Start-Sleep -Seconds 5
    }
}
Trigger the Microsoft Store to upgrade all apps.
Write-Host "Triggering Store to upgrade all apps..." -ForegroundColor Green
$namespaceName = "root\cimv2\mdm\dmmap"
$className = "MDM_EnterpriseModernAppManagement_AppManagement01"
$wmiObj = Get-WmiObject -Namespace $namespaceName -Class $className
$wmiObj.UpdateScanMethod() | Format-Table -AutoSize
Install necessary software from WinGet:
function Install-IfNotInstalled {
    param (
        [string]$package
    )

    if ("$(winget list -e --id $package --source winget)".Contains("--")) { 
        Write-Host "$package is already installed!" -ForegroundColor Green
    }
    else {
        Write-Host "Attempting to install: $package..." -ForegroundColor Green
        winget install -e --id $package --source winget
    }
}


Install-IfNotInstalled "Microsoft.WindowsTerminal"
Install-IfNotInstalled "Microsoft.Teams"
Install-IfNotInstalled "Microsoft.Office"
Install-IfNotInstalled "Microsoft.OneDrive"
Install-IfNotInstalled "Microsoft.PowerShell"
Install-IfNotInstalled "Microsoft.dotnet"
Install-IfNotInstalled "Microsoft.Edge"
Install-IfNotInstalled "Microsoft.EdgeWebView2Runtime"
Install-IfNotInstalled "Microsoft.AzureDataStudio"
Install-IfNotInstalled "Tencent.WeChat"
Install-IfNotInstalled "SoftDeluxe.FreeDownloadManager"
Install-IfNotInstalled "VideoLAN.VLC"
Install-IfNotInstalled "OBSProject.OBSStudio"
Install-IfNotInstalled "Git.Git"
Install-IfNotInstalled "OpenJS.NodeJS"
Install-IfNotInstalled "Postman.Postman"
Install-IfNotInstalled "7zip.7zip"
Install-IfNotInstalled "CPUID.CPU-Z"
Install-IfNotInstalled "WinDirStat.WinDirStat"
Install-IfNotInstalled "FastCopy.FastCopy"
Install-IfNotInstalled "DBBrowserForSQLite.DBBrowserForSQLite"
Install necessary Microsoft Store apps:
function Install-StoreApp {
    param (
        [string]$storeAppId,
        [string]$wingetAppName
    )

    if ("$(winget list --name $wingetAppName --exact --source msstore --accept-source-agreements)".Contains("--")) { 
        Write-Host "$wingetAppName is already installed!" -ForegroundColor Green
    }
    else {
        Write-Host "Attempting to download $wingetAppName..." -ForegroundColor Green
        winget install --id $storeAppId.ToUpper() --name $wingetAppName  --exact --source msstore --accept-package-agreements --accept-source-agreements
    }
}

Install-StoreApp -storeAppId "9NBLGGH5R558" -wingetAppName "Microsoft To Do"
Install-StoreApp -storeAppId "9MV0B5HZVK9Z" -wingetAppName "Xbox"
Install-StoreApp -storeAppId "9wzdncrfjbh4" -wingetAppName "Microsoft Photos"
Install-StoreApp -storeAppId "9nblggh4qghw" -wingetAppName "Microsoft Sticky Notes"
Install-StoreApp -storeAppId "9wzdncrfhvqm" -wingetAppName "Mail and Calendar"
Install-StoreApp -storeAppId "9ncbcszsjrsb" -wingetAppName "Spotify Music"
Install-StoreApp -storeAppId "9mspc6mp8fm4" -wingetAppName "Microsoft Whiteboard"
Install-StoreApp -storeAppId "9wzdncrfhvjl" -wingetAppName "OneNote for Windows 10"
Reload environment variables:
Write-Host "Reloading environment variables..." -ForegroundColor Green
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
Install Chromium (Requires FDM and 7zip to be installed first):
    Write-Host "Installing Chromium as backup browser ..." -ForegroundColor Green
    $chromiumUrl = "https://download-chromium.appspot.com/dl/Win_x64?type=snapshots"
    $chromiumPath = "${env:ProgramFiles}\Chromium"
    
    $downloadedChromium = $env:USERPROFILE + "\Downloads\Win_x64.zip"
    Remove-Item $downloadedChromium -ErrorAction SilentlyContinue
    Start-Process "$env:ProgramFiles\Softdeluxe\Free Download Manager\fdm.exe" -PassThru "$chromiumUrl -force"
        
    while(-not $(Get-Item $downloadedChromium -ErrorAction SilentlyContinue))
    {
        Write-Host "Chromium is still not downloaded!"
        Start-Sleep -Seconds 5
    }
    
    Move-Item $downloadedChromium "C:\chromium.zip" -Force
    
    & "${env:ProgramFiles}\7-Zip\7z.exe" x "C:\chromium.zip" "-o$($chromiumPath)" -y
    Remove-Item -Path "C:\chromium.zip" -Force

    $shortCutPath = $env:USERPROFILE + "\Start Menu\Programs" + "\Chromium.lnk"
    Remove-Item -Path $shortCutPath -Force -ErrorAction SilentlyContinue
    $objShell = New-Object -ComObject ("WScript.Shell")
    $objShortCut = $objShell.CreateShortcut($shortCutPath)
    $objShortCut.TargetPath = "$chromiumPath\chrome-win\Chrome.exe"
    $objShortCut.Save()
Install FFmpeg:
    Write-Host "Downloading FFmpeg..." -ForegroundColor Green
    $ffmpegPath = "C:\Program Files\FFMPEG"
    $downloadUri = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z"
    
    $downloadedFfmpeg = $env:USERPROFILE + "\Downloads\ffmpeg-git-full.7z"
    Remove-Item $downloadedFfmpeg -ErrorAction SilentlyContinue
    Start-Process "$env:ProgramFiles\Softdeluxe\Free Download Manager\fdm.exe" -PassThru "$downloadUri -force"
        
    while(-not $(Get-Item $downloadedFfmpeg -ErrorAction SilentlyContinue))
    {
        Write-Host "FFmpeg is still not downloaded!"
        Start-Sleep -Seconds 5
    }
    
    Move-Item $downloadedFfmpeg "C:\ffmpeg.7z" -Force
    
    & ${env:ProgramFiles}\7-Zip\7z.exe x "C:\ffmpeg.7z" "-o$($ffmpegPath)" -y
    $subPath = $(Get-ChildItem -Path $ffmpegPath | Where-Object { $_.Name -like "ffmpeg*" } | Sort-Object Name -Descending | Select-Object -First 1).Name
    $subPath = Join-Path -Path $ffmpegPath -ChildPath $subPath
    $binPath = Join-Path -Path $subPath -ChildPath "bin"
    Write-Host "Adding FFmpeg to PATH..." -ForegroundColor Green
    [Environment]::SetEnvironmentVariable(
        "Path",
        [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine) + ";$binPath",
        [EnvironmentVariableTarget]::Machine)
    Remove-Item -Path "C:\ffmpeg.7z" -Force
Sign in OneDrive based on the AAD identity:
$aad = Connect-AzureAD

Write-Host "Enabling OneDrive silent sign in..." -ForegroundColor Green
$HKLMregistryPath = 'HKLM:\SOFTWARE\Policies\Microsoft\OneDrive'##Path to HKLM keys
$DiskSizeregistryPath = 'HKLM:\SOFTWARE\Policies\Microsoft\OneDrive\DiskSpaceCheckThresholdMB'##Path to max disk size key
if(!(Test-Path $HKLMregistryPath)){New-Item -Path $HKLMregistryPath -Force}
if(!(Test-Path $DiskSizeregistryPath)){New-Item -Path $DiskSizeregistryPath -Force}

Write-Host "Current AAD Tenant Id is $($aad.TenantId)"
New-ItemProperty -Path $HKLMregistryPath -Name 'SilentAccountConfig' -Value '1' -PropertyType DWORD -Force | Out-Null ##Enable silent account configuration
New-ItemProperty -Path $DiskSizeregistryPath -Name $aad.TenantId -Value '102400' -PropertyType DWORD -Force | Out-Null ##Set max OneDrive threshold before prompting

Write-Host "Restarting OneDrive..." -ForegroundColor Yellow
taskkill.exe /IM OneDrive.exe /F
explorer "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\OneDrive.lnk"
explorer "$env:LOCALAPPDATA\Microsoft\OneDrive\OneDrive.exe"
explorer "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\OneDrive.lnk"

$OneDrivePath = $null
while ($null -eq $OneDrivePath -or -not $OneDrivePath.Contains("-")) {
    # Wait till it finds my enterprise OneDrive folder.
    Start-Sleep -Seconds 10
    $OneDrivePath = $(Get-ChildItem -Path $HOME | Where-Object { $_.Name -like "OneDrive*" } | Sort-Object Name -Descending | Select-Object -First 1).FullName
}
Get-ChildItem $OneDrivePath | Format-Table -AutoSize
Install your personal profile file (Requires your own profile file on GitHub):
Write-Host "Installing profile file..." -ForegroundColor Green
if (!(Test-Path $PROFILE))
{
   Write-Host "Creating PROFILE..." -ForegroundColor Yellow
   New-Item -Path $PROFILE -ItemType "file" -Force
}
$profileContent = (New-Object System.Net.WebClient).DownloadString('https://github.com/Anduin2017/configuration-script-win/raw/main/PROFILE.ps1')
Set-Content $PROFILE $profileContent
. $PROFILE
Link back SSH configuration from OneDrive (Requires you to setup your OneDrive files)
Write-Host "Linking back SSH keys..." -ForegroundColor Green
$oneDriveSshConfigPath = "$OneDrivePath\Storage\SSH\"
$localSshConfigPath = "$HOME\.ssh\"
$_ = Get-Content $oneDriveSshConfigPath\id_rsa.pub # Ensure file is available.

cmd /c "rmdir $localSshConfigPath /q"
cmd /c "mklink /d `"$localSshConfigPath`" `"$oneDriveSshConfigPath`""

Write-Host "Testing SSH features..." -ForegroundColor Green
Write-Host "yes" | ssh -o "StrictHostKeyChecking no" git@github.com
Setup Git (Requires Git.Git to be installed first):
$aad = Connect-AzureAD
$email = $aad.Account.Id
$name = (Get-AzureADUser -ObjectId $email).DisplayName

Write-Host "Configuring git..." -ForegroundColor Green
Write-Host "Setting git email to $email" -ForegroundColor Yellow
Write-Host "Setting git name to $name" -ForegroundColor Yellow
git config --global user.email $email
git config --global user.name $name
git config --global core.autocrlf true
Link back your Windows Terminal configuration file from OneDrive (Requires the file exists in your own OneDrive):
$OneDrivePath = $(Get-ChildItem -Path $HOME | Where-Object { $_.Name -like "OneDrive*" } | Sort-Object Name -Descending | Select-Object -First 1).FullName

Write-Host "Linking back windows terminal configuration file..." -ForegroundColor Green
$wtConfigPath = "$HOME\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json"
$onedriveConfigwt = "$OneDrivePath\Storage\WT\settings.json"

$_ = Get-Content $onedriveConfigwt # Ensure file is available.

cmd /c "del `"$wtConfigPath`""
cmd /c "mklink `"$wtConfigPath`" `"$onedriveConfigwt`""
Configure Windows terminal context menu (Requires Microsoft.PowerShell to be installed first):
Write-Host "Configuring windows terminal context menu..." -ForegroundColor Green
git clone https://github.com/lextm/windowsterminal-shell.git "$HOME\temp"
pwsh -command "$HOME\temp\install.ps1 mini"
Remove-Item $HOME\temp -Force -Recurse -Confirm:$false
Install some necessary node tools:
Write-Host "Setting up some node js global tools..." -ForegroundColor Green
npm install --global npm@latest
npm install --global node-static typescript @angular/cli yarn
Configure .NET development environment:
Write-Host "Setting up .NET environment variables..." -ForegroundColor Green
[Environment]::SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development", "Machine")
[Environment]::SetEnvironmentVariable("DOTNET_PRINT_TELEMETRY_MESSAGE", "false", "Machine")
[Environment]::SetEnvironmentVariable("DOTNET_CLI_TELEMETRY_OPTOUT", "1", "Machine")
Config Nuget:
if (-not (Test-Path -Path "$env:APPDATA\Nuget\Nuget.config") -or $null -eq (Select-String -Path "$env:APPDATA\Nuget\Nuget.config" -Pattern "nuget.org")) {
    $config = "<?xml version=`"1.0`" encoding=`"utf-8`"?>`
    <configuration>`
      <packageSources>`
        <add key=`"nuget.org`" value=`"https://api.nuget.org/v3/index.json`" protocolVersion=`"3`" />`
        <add key=`"Microsoft Visual Studio Offline Packages`" value=`"C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\`" />`
      </packageSources>`
      <config>`
        <add key=`"repositoryPath`" value=`"D:\CxCache`" />`
      </config>`
    </configuration>"
    Set-Content -Path "$env:APPDATA\Nuget\Nuget.config" -Value $config
} else {
    Write-Host "Nuget config file already exists." -ForegroundColor Yellow
}
New-Item -Path "C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\" -ItemType directory -Force

Write-Host "Installing Github.com/microsoft/artifacts-credprovider..." -ForegroundColor Green
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/microsoft/artifacts-credprovider/master/helpers/installcredprovider.ps1'))
Install Entity Framework:
dotnet tool install --global dotnet-ef --interactive
dotnet tool update --global dotnet-ef --interactive
Clear recycle bin:
Clear-RecycleBin -DriveLetter $driveLetter -Force -Confirm
Write-Host "Recycle bin cleared on $driveLetter..."
Disable active probing (Fix Windows 11 some strange issue):
Write-Host "Disabling rubbish Active Probing..." -ForegroundColor Green
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\NlaSvc\Parameters\Internet\" -Name EnableActiveProbing -Value 0 -Force
Write-Host "Disabled Active Probing."
Clean up Startup:
Write-Host "Clearing start up..." -ForegroundColor Green
$startUp = $env:USERPROFILE + "\Start Menu\Programs\StartUp\*"
Get-ChildItem $startUp
Remove-Item -Path $startUp
Get-ChildItem $startUp
Remove 3D objects (Works with Windows 10):
Write-Host "Remove rubbish 3D objects..." -ForegroundColor Green
Remove-Item 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}' -ErrorAction SilentlyContinue
Write-Host "3D objects deleted."
Setup Power policy to ultimate:
Write-Host "Setting Power Policy to ultimate..." -ForegroundColor Green
powercfg /s e9a42b02-d5df-448d-aa00-03f14749eb61
powercfg /list
Enable desktop icons (Migrated from CMD):
Write-Host "Enabling desktop icons..." -ForegroundColor Green
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\ClassicStartMenu /v {20D04FE0-3AEA-1069-A2D8-08002B30309D} /t REG_DWORD /d 0 /f"
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel /v {20D04FE0-3AEA-1069-A2D8-08002B30309D} /t REG_DWORD /d 0 /f"
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\ClassicStartMenu /v {59031a47-3f72-44a7-89c5-5595fe6b30ee} /t REG_DWORD /d 0 /f"
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel /v {59031a47-3f72-44a7-89c5-5595fe6b30ee} /t REG_DWORD /d 0 /f"
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\ClassicStartMenu /v {645FF040-5081-101B-9F08-00AA002F954E} /t REG_DWORD /d 0 /f"
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel /v {645FF040-5081-101B-9F08-00AA002F954E} /t REG_DWORD /d 0 /f"
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\ClassicStartMenu /v {F02C1A0D-BE21-4350-88B0-7367FC96EF3C} /t REG_DWORD /d 0 /f"
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel /v {F02C1A0D-BE21-4350-88B0-7367FC96EF3C} /t REG_DWORD /d 0 /f"
Disable sleeping on AC power:
Write-Host "Disable Sleep on AC Power..." -ForegroundColor Green
Powercfg /Change monitor-timeout-ac 20
Powercfg /Change standby-timeout-ac 0
Write-Host "Monitor timeout set to 20."
Enable Chinese input method:
Write-Host "Enabling Chinese input method..." -ForegroundColor Green
$LanguageList = Get-WinUserLanguageList
$LanguageList.Add("zh-CN")
Set-WinUserLanguageList $LanguageList -Force
$LanguageList | Format-Table -AutoSize
Remove obsolete bluetooth icon (Migrated from CMD):
Write-Host "Removing Bluetooth icons..." -ForegroundColor Green
cmd.exe /c "reg add `"HKCU\Control Panel\Bluetooth`" /v `"Notification Area Icon`" /t REG_DWORD /d 0 /f"
File explorer show ext, show disks, hide checkbox (Migrated from CMD):
Write-Host "Applying file explorer settings..." -ForegroundColor Green
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced /v HideFileExt /t REG_DWORD /d 0 /f"
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced /v AutoCheckSelect /t REG_DWORD /d 0 /f"
cmd.exe /c "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced /v LaunchTo /t REG_DWORD /d 1 /f"
Setup time to China:
Write-Host "Setting Time zone..." -ForegroundColor Green
Set-TimeZone -Name "China Standard Time"
Write-Host "Time zone set to China Standard Time."

Write-Host "Syncing time..." -ForegroundColor Green
net stop w32time
net start w32time
w32tm /resync /force
w32tm /query /status
Setup mouse speed to disable mouse accelerate:
Write-Host "Setting mouse speed..." -ForegroundColor Green
cmd.exe /c "reg add `"HKCU\Control Panel\Mouse`" /v MouseSensitivity /t REG_SZ /d 6 /f"
cmd.exe /c "reg add `"HKCU\Control Panel\Mouse`" /v MouseSpeed /t REG_SZ /d 0 /f"
cmd.exe /c "reg add `"HKCU\Control Panel\Mouse`" /v MouseThreshold1 /t REG_SZ /d 0 /f"
cmd.exe /c "reg add `"HKCU\Control Panel\Mouse`" /v MouseThreshold2 /t REG_SZ /d 0 /f"
Write-Host "Mouse speed changed. Will apply next reboot." -ForegroundColor Yellow
Pin important code folder to quick access:
Write-Host "Pin repos to quick access..." -ForegroundColor Green
$load_com = new-object -com shell.application
$load_com.Namespace("$env:USERPROFILE\source\repos").Self.InvokeVerb("pintohome")
Write-Host "Repos folder are pinned to file explorer."
Enable dark theme:
Write-Host "Enabling dark theme..." -ForegroundColor Green
Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize" -Name AppsUseLightTheme -Value 0
Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize" -Name SystemUsesLightTheme -Value 0
Write-Host "Dark theme enabled."
Clean and restart desktop (delete everything on desktop) (DANGEROUS):
Write-Host "Cleaning desktop..." -ForegroundColor Green
Remove-Item $HOME\Desktop\* -Force -Recurse -Confirm:$false -ErrorAction SilentlyContinue
Remove-Item "C:\Users\Public\Desktop\*" -Force -Recurse -Confirm:$false -ErrorAction SilentlyContinue

Write-Host "Resetting desktop..." -ForegroundColor Yellow
Stop-Process -Name explorer -Force
Write-Host "Desktop cleaned."
Trust current local network to enable more features (Dangerous, only run in Work or Home network):
$networkProfiles = Get-NetConnectionProfile
foreach ($networkProfile in $networkProfiles) {
    Write-Host "Setting network $($networkProfile.Name) to home network to enable more features..." -ForegroundColor Green
    Write-Host "This is dangerous because your roommates may detect your device is online." -ForegroundColor Yellow
    Set-NetConnectionProfile -Name $networkProfile.Name -NetworkCategory Private
}
Set up UAC to default protection policy:
Write-Host "Setting UAC..." -ForegroundColor Green
Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\" -Name "ConsentPromptBehaviorAdmin" -Value 5
Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\" -Name "PromptOnSecureDesktop" -Value 1
Enable remote desktop connection (Dangerous. Only add if you need):
Write-Host "Enable Remote Desktop..." -ForegroundColor Green
Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\" -Name "fDenyTSConnections" -Value 0
Set-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\" -Name "UserAuthentication" -Value 0
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
Upgrade all apps:
winget upgrade --all --source winget
winget upgrade --all --source msstore
Check Windows updates:
    Write-Host "Checking for windows updates..." -ForegroundColor Green
    Install-Module -Name PSWindowsUpdate -Force
    Write-Host "Installing updates... (Computer will reboot in minutes...)" -ForegroundColor Green
    Get-WindowsUpdate -AcceptAll -Install -ForceInstall -AutoReboot