Skip to content

Instantly share code, notes, and snippets.

@dalraf
Last active January 14, 2026 12:37
Show Gist options
  • Select an option

  • Save dalraf/d56063ef0283869174650ffa81617828 to your computer and use it in GitHub Desktop.

Select an option

Save dalraf/d56063ef0283869174650ffa81617828 to your computer and use it in GitHub Desktop.
Clonagem Windows
<#
.SYNOPSIS
Script de preparação para Sysprep no Windows 11.
Resolve erros de Appx (Copilot), Reserved Storage e pacotes pendentes.
#>
# 1. Verificar privilégios de Administrador
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Error "Por favor, execute este script como Administrador."
exit
}
Write-Host "--- Iniciando limpeza profunda para Sysprep ---" -ForegroundColor Cyan
# 2. Parar serviços que interferem na remoção de pacotes
Write-Host "[1/6] Parando serviços de atualização..." -ForegroundColor Yellow
Stop-Service -Name wuauserv, bits, dispbroker -Force -ErrorAction SilentlyContinue
# 3. Desativar o Armazenamento Reservado (Reserved Storage)
# Resolve o erro 0x800F0975 relatado no log
Write-Host "[2/6] Desativando Armazenamento Reservado..." -ForegroundColor Yellow
Set-WindowsReservedStorageState -State Disabled -ErrorAction SilentlyContinue
# 4. Remover pacotes Appx problemáticos (Foco no Microsoft.Copilot)
Write-Host "[3/6] Removendo apps problemáticos (Copilot, Bing, etc)..." -ForegroundColor Yellow
$AppsList = @("*Copilot*", "*Bing*", "*OfficeHub*", "*SkypeApp*", "*ZuneVideo*", "*ZuneMusic*", "*Weather*", "*News*", "*SolitaireCollection*")
foreach ($AppName in $AppsList) {
# Remove do perfil do usuário atual e de todos os outros
Get-AppxPackage -AllUsers $AppName | Remove-AppxPackage -AllUsers -ErrorAction SilentlyContinue
# Remove do provisionamento da imagem (impede que volte)
Get-AppxProvisionedPackage -Online | Where-Object {$_.PackageName -like $AppName} | Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue
}
# 5. Limpeza geral de pacotes (Opcional - Preserva Loja e Calculadora)
Write-Host "[4/6] Limpando demais pacotes Appx não essenciais..." -ForegroundColor Yellow
Get-AppxPackage -AllUsers | Where-Object {$_.Name -notlike "*WindowsStore*" -and $_.Name -notlike "*Calculator*"} | Remove-AppxPackage -AllUsers -ErrorAction SilentlyContinue
Get-AppxProvisionedPackage -Online | Where-Object {$_.DisplayName -notlike "*WindowsStore*" -and $_.DisplayName -notlike "*Calculator*"} | Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue
# 6. Corrigir chaves de registro do Sysprep (Caso o sistema tenha sido atualizado)
Write-Host "[5/6] Ajustando chaves de registro do Sysprep..." -ForegroundColor Yellow
$RegistryPath = "HKLM:\SYSTEM\Setup\Status\SysprepStatus"
if (Test-Path $RegistryPath) {
Set-ItemProperty -Path $RegistryPath -Name "CleanupState" -Value 2
Set-ItemProperty -Path $RegistryPath -Name "GeneralizationState" -Value 7
}
# Remove a chave que bloqueia sysprep em sistemas que sofreram upgrade
Remove-ItemProperty -Path "HKLM:\System\Setup" -Name "Upgrade" -ErrorAction SilentlyContinue
# 7. Finalização e limpeza de arquivos temporários
Write-Host "[6/6] Limpando logs e filas pendentes..." -ForegroundColor Yellow
$SysprepPanther = "C:\Windows\System32\Sysprep\Panther"
if (Test-Path $SysprepPanther) {
Remove-Item -Path "$SysprepPanther\*" -Recurse -Force -ErrorAction SilentlyContinue
}
Write-Host "--- LIMPEZA CONCLUÍDA ---" -ForegroundColor Green
Write-Host "RECOMENDAÇÕES:" -ForegroundColor White
Write-Host "1. REINICIE o computador agora (ele voltará para o Modo de Auditoria)."
Write-Host "2. Mantenha a INTERNET DESCONECTADA."
Write-Host "3. Execute o comando do Sysprep na janela que aparecer."
Write-Host ""
@echo off
:: Verifica se está rodando como Administrador
net session >nul 2>&1
if %errorLevel% neq 0 (
echo Por favor, execute este script como Administrador.
pause
exit
)
:: 1. Cria a pasta Panther se não existir
if not exist "C:\Windows\Panther" mkdir "C:\Windows\Panther"
:: 2. Copia o arquivo para os dois locais necessários
:: O local Panther é onde o script interno do XML vai buscar as configurações extras
copy /y "unattend.xml" "C:\Windows\Panther\unattend.xml"
:: O local Sysprep é onde o comando vai ler as instruções de generalização
copy /y "unattend.xml" "C:\Windows\System32\Sysprep\unattend.xml"
:: 3. Executa o Sysprep
echo Iniciando Sysprep e Generalizacao...
cd /d "C:\Windows\System32\Sysprep"
sysprep.exe /generalize /oobe /shutdown /unattend:"C:\Windows\System32\Sysprep\unattend.xml"
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
<!--https://schneegans.de/windows/unattend-generator/?LanguageMode=Unattended&UILanguage=pt-BR&Locale=pt-BR&Keyboard=00000416&GeoLocation=32&ProcessorArchitecture=amd64&BypassRequirementsCheck=true&ComputerNameMode=Random&CompactOsMode=Default&TimeZoneMode=Implicit&PartitionMode=Interactive&DiskAssertionMode=Skip&WindowsEditionMode=Generic&WindowsEdition=pro&InstallFromMode=Automatic&PEMode=Default&UserAccountMode=Unattended&AccountName0=usuario&AccountDisplayName0=Usu%C3%A1rio&AccountPassword0=1234&AccountGroup0=Administrators&AutoLogonMode=Own&PasswordExpirationMode=Unlimited&LockoutMode=Default&HideFiles=Hidden&TaskbarSearch=Box&TaskbarIconsMode=Default&StartTilesMode=Default&StartPinsMode=Default&EffectsMode=Default&DesktopIconsMode=Default&StartFoldersMode=Default&WifiMode=Interactive&ExpressSettings=DisableAll&LockKeysMode=Skip&StickyKeysMode=Default&ColorMode=Default&WallpaperMode=Default&LockScreenMode=Default&WdacMode=Skip&AppLockerMode=Skip-->
<settings pass="offlineServicing"></settings>
<settings pass="windowsPE">
<component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<UILanguage>pt-BR</UILanguage>
</component>
<component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<UserData>
<ProductKey>
<Key>VK7JG-NPHTM-C97JM-9MPGT-3V66T</Key>
<WillShowUI>OnError</WillShowUI>
</ProductKey>
<AcceptEula>true</AcceptEula>
</UserData>
<UseConfigurationSet>false</UseConfigurationSet>
<RunSynchronous>
<RunSynchronousCommand wcm:action="add">
<Order>1</Order>
<Path>reg.exe add "HKLM\SYSTEM\Setup\LabConfig" /v BypassTPMCheck /t REG_DWORD /d 1 /f</Path>
</RunSynchronousCommand>
<RunSynchronousCommand wcm:action="add">
<Order>2</Order>
<Path>reg.exe add "HKLM\SYSTEM\Setup\LabConfig" /v BypassSecureBootCheck /t REG_DWORD /d 1 /f</Path>
</RunSynchronousCommand>
<RunSynchronousCommand wcm:action="add">
<Order>3</Order>
<Path>reg.exe add "HKLM\SYSTEM\Setup\LabConfig" /v BypassRAMCheck /t REG_DWORD /d 1 /f</Path>
</RunSynchronousCommand>
</RunSynchronous>
</component>
</settings>
<settings pass="generalize"></settings>
<settings pass="specialize">
<component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<RunSynchronous>
<RunSynchronousCommand wcm:action="add">
<Order>1</Order>
<Path>powershell.exe -WindowStyle "Normal" -NoProfile -Command "$xml = [xml]::new(); $xml.Load('C:\Windows\Panther\unattend.xml'); $sb = [scriptblock]::Create( $xml.unattend.Extensions.ExtractScript ); Invoke-Command -ScriptBlock $sb -ArgumentList $xml;"</Path>
</RunSynchronousCommand>
<RunSynchronousCommand wcm:action="add">
<Order>2</Order>
<Path>powershell.exe -WindowStyle "Normal" -ExecutionPolicy "Unrestricted" -NoProfile -File "C:\Windows\Setup\Scripts\Specialize.ps1"</Path>
</RunSynchronousCommand>
</RunSynchronous>
</component>
</settings>
<settings pass="auditSystem"></settings>
<settings pass="auditUser"></settings>
<settings pass="oobeSystem">
<component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<InputLocale>0416:00000416</InputLocale>
<SystemLocale>pt-BR</SystemLocale>
<UILanguage>pt-BR</UILanguage>
<UserLocale>pt-BR</UserLocale>
</component>
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<UserAccounts>
<LocalAccounts>
<LocalAccount wcm:action="add">
<Name>usuario</Name>
<DisplayName>Usu&#xE1;rio</DisplayName>
<Group>Administrators</Group>
<Password>
<Value>1234</Value>
<PlainText>true</PlainText>
</Password>
</LocalAccount>
</LocalAccounts>
</UserAccounts>
<AutoLogon>
<Username>usuario</Username>
<Enabled>true</Enabled>
<LogonCount>1</LogonCount>
<Password>
<Value>1234</Value>
<PlainText>true</PlainText>
</Password>
</AutoLogon>
<OOBE>
<ProtectYourPC>3</ProtectYourPC>
<HideEULAPage>true</HideEULAPage>
<HideWirelessSetupInOOBE>false</HideWirelessSetupInOOBE>
<HideOnlineAccountScreens>false</HideOnlineAccountScreens>
</OOBE>
<FirstLogonCommands>
<SynchronousCommand wcm:action="add">
<Order>1</Order>
<CommandLine>powershell.exe -WindowStyle "Normal" -ExecutionPolicy "Unrestricted" -NoProfile -File "C:\Windows\Setup\Scripts\FirstLogon.ps1"</CommandLine>
</SynchronousCommand>
</FirstLogonCommands>
</component>
</settings>
<Extensions xmlns="https://schneegans.de/windows/unattend-generator/">
<ExtractScript>
param(
[xml] $Document
);
foreach( $file in $Document.unattend.Extensions.File ) {
$path = [System.Environment]::ExpandEnvironmentVariables( $file.GetAttribute( 'path' ) );
mkdir -Path( $path | Split-Path -Parent ) -ErrorAction 'SilentlyContinue';
$encoding = switch( [System.IO.Path]::GetExtension( $path ) ) {
{ $_ -in '.ps1', '.xml' } { [System.Text.Encoding]::UTF8; }
{ $_ -in '.reg', '.vbs', '.js' } { [System.Text.UnicodeEncoding]::new( $false, $true ); }
default { [System.Text.Encoding]::Default; }
};
$bytes = $encoding.GetPreamble() + $encoding.GetBytes( $file.InnerText.Trim() );
[System.IO.File]::WriteAllBytes( $path, $bytes );
}
</ExtractScript>
<File path="C:\Windows\Setup\Scripts\Specialize.ps1">
$scripts = @(
{
reg.exe add "HKLM\SYSTEM\Setup\MoSetup" /v AllowUpgradesWithUnsupportedTPMOrCPU /t REG_DWORD /d 1 /f;
};
{
net.exe accounts /maxpwage:UNLIMITED;
};
);
&amp; {
[float] $complete = 0;
[float] $increment = 100 / $scripts.Count;
foreach( $script in $scripts ) {
Write-Progress -Activity 'Running scripts to customize your Windows installation. Do not close this window.' -PercentComplete $complete;
'*** Will now execute command &#xAB;{0}&#xBB;.' -f $(
$str = $script.ToString().Trim() -replace '\s+', ' ';
$max = 100;
if( $str.Length -le $max ) {
$str;
} else {
$str.Substring( 0, $max - 1 ) + '&#x2026;';
}
);
$start = [datetime]::Now;
&amp; $script;
'*** Finished executing command after {0:0} ms.' -f [datetime]::Now.Subtract( $start ).TotalMilliseconds;
"`r`n" * 3;
$complete += $increment;
}
} *&gt;&amp;1 | Out-String -Width 1KB -Stream &gt;&gt; "C:\Windows\Setup\Scripts\Specialize.log";
</File>
<File path="C:\Windows\Setup\Scripts\FirstLogon.ps1">
$scripts = @(
{
Set-ItemProperty -LiteralPath 'Registry::HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name 'AutoLogonCount' -Type 'DWord' -Force -Value 0;
};
{
Remove-Item -LiteralPath @(
'C:\Windows\Panther\unattend.xml';
'C:\Windows\Panther\unattend-original.xml';
'C:\Windows\Setup\Scripts\Wifi.xml';
) -Force -ErrorAction 'SilentlyContinue' -Verbose;
};
);
&amp; {
[float] $complete = 0;
[float] $increment = 100 / $scripts.Count;
foreach( $script in $scripts ) {
Write-Progress -Activity 'Running scripts to finalize your Windows installation. Do not close this window.' -PercentComplete $complete;
'*** Will now execute command &#xAB;{0}&#xBB;.' -f $(
$str = $script.ToString().Trim() -replace '\s+', ' ';
$max = 100;
if( $str.Length -le $max ) {
$str;
} else {
$str.Substring( 0, $max - 1 ) + '&#x2026;';
}
);
$start = [datetime]::Now;
&amp; $script;
'*** Finished executing command after {0:0} ms.' -f [datetime]::Now.Subtract( $start ).TotalMilliseconds;
"`r`n" * 3;
$complete += $increment;
}
} *&gt;&amp;1 | Out-String -Width 1KB -Stream &gt;&gt; "C:\Windows\Setup\Scripts\FirstLogon.log";
</File>
</Extensions>
</unattend>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment