add packer stuff

This commit is contained in:
Dax T. Games
2023-03-17 09:30:14 -04:00
parent bc0db6a7b6
commit 600552f061
35 changed files with 1803 additions and 1 deletions

View File

@ -0,0 +1 @@
powershell -NoProfile -ExecutionPolicy unrestricted -Command "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))"

View File

@ -0,0 +1,26 @@
choco install -y boxstarter.winconfig
# Editors
choco install -y notepadplusplus
# Terminals
choco install -y microsoft-windows-terminal
choco install -y fluent-terminal
choco install -y hyper
choco install -y tabby
choco install -y conemu
# other
choco install -y poshgit
# IDE/Software development
choco install -y vscode
choco install -y visualstudio2022community --execution-timeout 9000 --package-parameters "--add Microsoft.VisualStudio.Workload.NativeDesktop;includeRecommended"
md C:\users\vagrant\bin
if (test-path "a:/set-shortcut.ps1") {
copy "a:/set-shortcut.ps1" C:\users\vagrant\bin
} elseif (test-path "e:/set-shortcut.ps1") {
copy "e:/set-shortcut.ps1" C:\users\vagrant\bin
}

View File

@ -0,0 +1,39 @@
if "%PACKER_BUILDER_TYPE:~0,6%"=="hyperv" (
echo "Skip compact steps in Hyper-V build."
goto :eof
)
if not exist "C:\Windows\Temp\7z1900-x64.msi" (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('https://www.7-zip.org/a/7z1900-x64.msi', 'C:\Windows\Temp\7z1900-x64.msi')" <NUL
)
msiexec /qb /i C:\Windows\Temp\7z1900-x64.msi
if not exist "C:\Windows\Temp\ultradefrag.zip" (
powershell -Command "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; (New-Object System.Net.WebClient).DownloadFile('https://downloads.sourceforge.net/project/ultradefrag/stable-release/6.1.0/ultradefrag-portable-6.1.0.bin.amd64.zip', 'C:\Windows\Temp\ultradefrag.zip')" <NUL
)
if not exist "C:\Windows\Temp\ultradefrag-portable-6.1.0.amd64\udefrag.exe" (
cmd /c ""C:\Program Files\7-Zip\7z.exe" x C:\Windows\Temp\ultradefrag.zip -oC:\Windows\Temp"
)
if not exist "C:\Windows\Temp\SDelete.zip" (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('https://download.sysinternals.com/files/SDelete.zip', 'C:\Windows\Temp\SDelete.zip')" <NUL
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('https://vagrantboxes.blob.core.windows.net/box/sdelete/v1.6.1/sdelete.exe', 'C:\Windows\Temp\sdelete.exe')" <NUL
)
if not exist "C:\Windows\Temp\sdelete.exe" (
cmd /c ""C:\Program Files\7-Zip\7z.exe" x C:\Windows\Temp\SDelete.zip -oC:\Windows\Temp"
)
msiexec /qb /x C:\Windows\Temp\7z1900-x64.msi
net stop wuauserv
rmdir /S /Q C:\Windows\SoftwareDistribution\Download
mkdir C:\Windows\SoftwareDistribution\Download
net start wuauserv
if "%PACKER_BUILDER_TYPE%" neq "hyperv-iso" (
cmd /c C:\Windows\Temp\ultradefrag-portable-6.1.0.amd64\udefrag.exe --optimize --repeat C:
cmd /c %SystemRoot%\System32\reg.exe ADD HKCU\Software\Sysinternals\SDelete /v EulaAccepted /t REG_DWORD /d 1 /f
cmd /c C:\Windows\Temp\sdelete.exe -q -z C:
)

View File

@ -0,0 +1,17 @@
::http://support.microsoft.com/kb/2570538
::http://robrelyea.wordpress.com/2007/07/13/may-be-helpful-ngen-exe-executequeueditems/
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" goto 64BIT
%windir%\microsoft.net\framework\v4.0.30319\ngen.exe update /force /queue > NUL
%windir%\microsoft.net\framework\v4.0.30319\ngen.exe executequeueditems > NUL
exit 0
:64BIT
%windir%\microsoft.net\framework\v4.0.30319\ngen.exe update /force /queue > NUL
%windir%\microsoft.net\framework64\v4.0.30319\ngen.exe update /force /queue > NUL
%windir%\microsoft.net\framework\v4.0.30319\ngen.exe executequeueditems > NUL
%windir%\microsoft.net\framework64\v4.0.30319\ngen.exe executequeueditems > NUL
exit 0

View File

@ -0,0 +1,33 @@
if ($env:PACKER_BUILDER_TYPE -And $($env:PACKER_BUILDER_TYPE).startsWith("hyperv")) {
Write-Output Skip debloat steps in Hyper-V build.
}
else {
Write-Output Downloading debloat zip
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$url = "https://github.com/StefanScherer/Debloat-Windows-10/archive/master.zip"
(New-Object System.Net.WebClient).DownloadFile($url, "$env:TEMP\debloat.zip")
Expand-Archive -Path $env:TEMP\debloat.zip -DestinationPath $env:TEMP -Force
#Write-Output Disable scheduled tasks
#. $env:TEMP\Debloat-Windows-10-master\utils\disable-scheduled-tasks.ps1
#Write-Output Block telemetry
#. $env:TEMP\Debloat-Windows-10-master\scripts\block-telemetry.ps1
#Write-Output Disable services
#. $env:TEMP\Debloat-Windows-10-master\scripts\disable-services.ps1
Write-Output Disable Windows Defender
if ($(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ProductName.StartsWith("Windows 10")) {
. $env:TEMP\Debloat-Windows-10-master\scripts\disable-windows-defender.ps1
}
else {
Uninstall-WindowsFeature Windows-Defender
}
Write-Output Optimize Windows Update
. $env:TEMP\Debloat-Windows-10-master\scripts\optimize-windows-update.ps1
#Write-Output Disable Windows Update
#Set-Service wuauserv -StartupType Disabled
#Write-Output Remove OneDrive
#. $env:TEMP\Debloat-Windows-10-master\scripts\remove-onedrive.ps1
Remove-Item $env:TEMP\debloat.zip
Remove-Item -recurse $env:TEMP\Debloat-Windows-10-master
}

View File

@ -0,0 +1,20 @@
rem http://www.windows-commandline.com/disable-automatic-updates-command-line/
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v AUOptions /t REG_DWORD /d 1 /f
rem remove optional WSUS server settings
reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" /f
rem even harder, disable windows update service
rem sc config wuauserv start= disabled
rem net stop wuauserv
set logfile=C:\Windows\Temp\win-updates.log
if exist %logfile% (
echo Show Windows Updates log file %logfile%
dir %logfile%
type %logfile%
rem output of type command is not fully shown in packer/ssh session, so try PowerShell
rem but it will hang if log file is about 22 KByte
rem powershell -command "Get-Content %logfile%"
echo End of Windows Updates log file %logfile%
)

View File

@ -0,0 +1,4 @@
Write-Output "Disabling Screensaver"
Set-ItemProperty "HKCU:\Control Panel\Desktop" -Name ScreenSaveActive -Value 0 -Type DWord
& powercfg -x -monitor-timeout-ac 0
& powercfg -x -monitor-timeout-dc 0

View File

@ -0,0 +1,8 @@
netsh advfirewall firewall set rule name="Windows Remote Management (HTTP-In)" new enable=yes action=block
netsh advfirewall firewall set rule group="Windows Remote Management" new enable=yes
$winrmService = Get-Service -Name WinRM
if ($winrmService.Status -eq "Running") {
Disable-PSRemoting -Force
}
Stop-Service winrm
Set-Service -Name winrm -StartupType Disabled

View File

@ -0,0 +1,4 @@
$DefenderInstalled = Get-Command -Module Defender
if($null -ne $DefenderInstalled) {
Set-MpPreference -DisableRealtimeMonitoring $true
}

View File

@ -0,0 +1,2 @@
netsh advfirewall firewall add rule name="Open Port 3389" dir=in action=allow protocol=TCP localport=3389
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

View File

@ -0,0 +1,27 @@
write-host "==> 'enable-winrm.ps1' - START..."
write-host "====> Getting Connections..."
Get-NetConnectionProfile | Set-NetConnectionProfile -NetworkCategory Private
write-host "====> Enable PSRemoting..."
Enable-PSRemoting -Force
write-host "====> WINRM Quick Config..."
winrm quickconfig -q
winrm quickconfig -transport:http
write-host "====> WINRM Set Config..."
winrm set winrm/config '@{MaxTimeoutms="1800000"}'
winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="800"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'
winrm set winrm/config/client/auth '@{Basic="true"}'
winrm set winrm/config/listener?Address=*+Transport=HTTP '@{Port="5985"}'
write-host "====> Configure Firewall..."
netsh advfirewall firewall set rule group="Windows Remote Administration" new enable=yes
netsh advfirewall firewall set rule name="Windows Remote Management (HTTP-In)" new enable=yes action=allow remoteip=any
write-host "====> Set WINRM Service Statup..."
Set-Service winrm -startuptype "auto"
write-host "====> Restart WINRM Service..."
Restart-Service winrm
write-host "==> 'enable-winrm.ps1' - END..."

View File

@ -0,0 +1,30 @@
# You cannot enable Windows PowerShell Remoting on network connections that are set to Public
# Spin through all the network locations and if they are set to Public, set them to Private
# using the INetwork interface:
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa370750(v=vs.85).aspx
# For more info, see:
# http://blogs.msdn.com/b/powershell/archive/2009/04/03/setting-network-location-to-private.aspx
function Set-NetworkTypeToPrivate {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPositionalParameters', '')]
param()
# Network location feature was only introduced in Windows Vista - no need to bother with this
# if the operating system is older than Vista
if ([environment]::OSVersion.version.Major -lt 6) { return }
# You cannot change the network location if you are joined to a domain, so abort
if (1, 3, 4, 5 -contains (Get-CimInstance win32_computersystem).DomainRole) { return }
# Get network connections
$networkListManager = [Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"{DCB00C01-570F-4A9B-8D69-199FDBA5723B}"))
$connections = $networkListManager.GetNetworkConnections()
$connections | ForEach-Object {
Write-Output $_.GetNetwork().GetName() "category was previously set to" $_.GetNetwork().GetCategory()
#$_.GetNetwork().SetCategory(1)
Write-Output $_.GetNetwork().GetName() "changed to category" $_.GetNetwork().GetCategory()
}
}
Set-NetworkTypeToPrivate

View File

@ -0,0 +1,12 @@
net stop wuauserv
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v EnableFeaturedSoftware /t REG_DWORD /d 1 /f
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v IncludeRecommendedUpdates /t REG_DWORD /d 1 /f
echo Set ServiceManager = CreateObject("Microsoft.Update.ServiceManager") > "%temp%\temp.vbs"
echo Set NewUpdateService = ServiceManager.AddService2("7971f918-a847-4430-9279-4a52d1efe18d",7,"") >> "%temp%\temp.vbs"
cscript "%temp%\temp.vbs"
net start wuauserv

View File

@ -0,0 +1,12 @@
Stop-Service -Name 'wuauserv'
Set-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update' -Name 'EnableFeaturedSoftware' -Value 1 -Type DWord
Set-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update' -Name 'IncludeRecommendedUpdates' -Value 1 -Type DWord
"Set ServiceManager = CreateObject(""Microsoft.Update.ServiceManager"")" | Out-File -FilePath 'C:\temp.vbs'
"Set NewUpdateService = ServiceManager.AddService2(""7971f918-a847-4430-9279-4a52d1efe18d"",7,"""")" | Out-File -FilePath 'C:\temp.vbs' -Append
cscript C:\temp.vbs
Remove-Item -Path 'C:\temp.vbs' -Force
Start-Service -Name 'wuauserv'

View File

@ -0,0 +1,16 @@
rem https://connect.microsoft.com/PowerShell/feedback/details/1609288/pin-to-taskbar-no-longer-working-in-windows-10
set ps_link=A:\WindowsPowerShell.lnk
if exist e:\WindowsPowerShell.lnk (
set ps_link=e:\WindowsPowerShell.lnk
)
set pin_to_10=A:\PinTo10.exe
if exist e:\PinTo10.exe (
set pin_to_10=e:\PinTo10.exe
)
copy "%ps_link%" "%TEMP%\Windows PowerShell.lnk"
%pin_to_10% /PTFOL01:'%TEMP%' /PTFILE01:'Windows PowerShell.lnk'
exit /b 0

View File

@ -0,0 +1,19 @@
Try {
Write-Output "Set power plan to high performance"
$HighPerf = powercfg -l | ForEach-Object { if ($_.contains("High performance")) { $_.split()[3] } }
# $HighPerf cannot be $null, we try activate this power profile with powercfg
if ($null -eq $HighPerf) {
throw "Error: HighPerf is null"
}
$CurrPlan = $(powercfg -getactivescheme).split()[3]
if ($CurrPlan -ne $HighPerf) { powercfg -setactive $HighPerf }
}
Catch {
Write-Warning -Message "Unable to set power plan to high performance"
Write-Warning $Error[0]
}

View File

@ -0,0 +1,21 @@
[CmdletBinding()]
param(
[Parameter()]
[string]$SourceExe,
[string]$Arguments,
[string]$DestinationPath,
[string]$WorkingDirectory,
[String]$IconLocation
)
if ($IconLocation -eq '') {
$IconLocation = $SourceExe
}
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($destinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $Arguments
$shortcut.WorkingDirectory = $WorkingDirectory
$shortcut.IconLocation = $IconLocation
$Shortcut.Save()

View File

@ -0,0 +1,2 @@
echo Set WinRM start type to auto
sc config winrm start= auto

View File

@ -0,0 +1 @@
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /f /v EnableLUA /t REG_DWORD /d 1

View File

@ -0,0 +1,96 @@
if (!( Test-Path "C:\Windows\Temp\7z1900-x64.msi")) {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; (New-Object System.Net.WebClient).DownloadFile('https://www.7-zip.org/a/7z1900-x64.msi', 'C:\Windows\Temp\7z1900-x64.msi')
}
if (!(Test-Path "C:\Windows\Temp\7z1900-x64.msi")) {
Start-Sleep 5; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; (New-Object System.Net.WebClient).DownloadFile('https://www.7-zip.org/a/7z1900-x64.msi', 'C:\Windows\Temp\7z1900-x64.msi')
}
cmd /c msiexec /qb /i C:\Windows\Temp\7z1900-x64.msi
if ("$env:PACKER_BUILDER_TYPE" -eq "vmware-iso") {
Write-Output "Using VMware"
if (Test-Path "C:\Users\vagrant\windows.iso") {
Move-Item -force C:\Users\vagrant\windows.iso C:\Windows\Temp
}
if (!(Test-Path "C:\Windows\Temp\windows.iso")) {
Try {
# Disabling the progress bar speeds up IWR https://github.com/PowerShell/PowerShell/issues/2138
$ProgressPreference = 'SilentlyContinue'
$pageContentLinks = (Invoke-WebRequest('https://softwareupdate.vmware.com/cds/vmw-desktop/ws') -UseBasicParsing).Links | where-object { $_.href -Match "[0-9]" } | Select-Object href | ForEach-Object { $_.href.Trim('/') }
$versionObject = $pageContentLinks | ForEach-Object { new-object System.Version ($_) } | sort-object -Descending | select-object -First 1 -Property:Major, Minor, Build
$newestVersion = $versionObject.Major.ToString() + "." + $versionObject.Minor.ToString() + "." + $versionObject.Build.ToString() | out-string
$newestVersion = $newestVersion.TrimEnd("`r?`n")
$nextURISubdirectoryObject = (Invoke-WebRequest("https://softwareupdate.vmware.com/cds/vmw-desktop/ws/$newestVersion/") -UseBasicParsing).Links | where-object { $_.href -Match "[0-9]" } | Select-Object href | where-object { $_.href -Match "[0-9]" }
$nextUriSubdirectory = $nextURISubdirectoryObject.href | Out-String
$nextUriSubdirectory = $nextUriSubdirectory.TrimEnd("`r?`n")
$newestVMwareToolsURL = "https://softwareupdate.vmware.com/cds/vmw-desktop/ws/$newestVersion/$nextURISubdirectory/windows/packages/tools-windows.tar"
Write-Output "The latest version of VMware tools has been determined to be downloadable from $newestVMwareToolsURL"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; (New-Object System.Net.WebClient).DownloadFile("$newestVMwareToolsURL", 'C:\Windows\Temp\vmware-tools.tar')
}
Catch {
Write-Output "Unable to determine the latest version of VMware tools. Falling back to hardcoded URL."
(New-Object System.Net.WebClient).DownloadFile('https://softwareupdate.vmware.com/cds/vmw-desktop/ws/15.5.5/16285975/windows/packages/tools-windows.tar', 'C:\Windows\Temp\vmware-tools.tar')
}
cmd /c "C:\PROGRA~1\7-Zip\7z.exe" x C:\Windows\Temp\vmware-tools.tar -oC:\Windows\Temp
Move-Item c:\windows\temp\VMware-tools-windows-*.iso c:\windows\temp\windows.iso
Try { Remove-Item "C:\Program Files (x86)\VMWare" -Recurse -Force -ErrorAction Stop } Catch { Write-Output "Directory didn't exist to be removed." }
}
cmd /c "C:\PROGRA~1\7-Zip\7z.exe" x "C:\Windows\Temp\windows.iso" -oC:\Windows\Temp\VMWare
cmd /c C:\Windows\Temp\VMWare\setup.exe /S /v"/qn REBOOT=R\"
Remove-Item -Force "C:\Windows\Temp\vmware-tools.tar"
Remove-Item -Force "C:\Windows\Temp\windows.iso"
Remove-Item -Force -Recurse "C:\Windows\Temp\VMware"
}
if ("$env:PACKER_BUILDER_TYPE" -eq "virtualbox-iso") {
Write-Output "Using Virtualbox"
if (Test-Path "C:\Users\vagrant\VBoxGuestAdditions.iso") {
Move-Item -Force C:\Users\vagrant\VBoxGuestAdditions.iso C:\Windows\Temp
}
if (!(Test-Path "C:\Windows\Temp\VBoxGuestAdditions.iso")) {
Try {
$pageContentLinks = (Invoke-WebRequest('https://download.virtualbox.org/virtualbox') -UseBasicParsing).Links | where-object { $_.href -Match "[0-9]" } | Select-Object href | where-object { $_.href -NotMatch "BETA" } | where-object { $_.href -NotMatch "RC" } | where-object { $_.href -Match "[0-9]\.[0-9]" } | ForEach-Object { $_.href.Trim('/') }
$versionObject = $pageContentLinks | ForEach-Object { new-object System.Version ($_) } | sort-object -Descending | select-object -First 1 -Property:Major, Minor, Build
$newestVersion = $versionObject.Major.ToString() + "." + $versionObject.Minor.ToString() + "." + $versionObject.Build.ToString() | out-string
$newestVersion = $newestVersion.TrimEnd("`r?`n")
$nextURISubdirectoryObject = (Invoke-WebRequest("https://download.virtualbox.org/virtualbox/$newestVersion/") -UseBasicParsing).Links | Select-Object href | where-object { $_.href -Match "GuestAdditions" }
$nextUriSubdirectory = $nextURISubdirectoryObject.href | Out-String
$nextUriSubdirectory = $nextUriSubdirectory.TrimEnd("`r?`n")
$newestVboxToolsURL = "https://download.virtualbox.org/virtualbox/$newestVersion/$nextUriSubdirectory"
Write-Output "The latest version of VirtualBox tools has been determined to be downloadable from $newestVboxToolsURL"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; (New-Object System.Net.WebClient).DownloadFile("$newestVboxToolsURL", 'C:\Windows\Temp\VBoxGuestAdditions.iso')
}
Catch {
Write-Output "Unable to determine the latest version of VBox tools. Falling back to hardcoded URL."
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; (New-Object System.Net.WebClient).DownloadFile('https://download.virtualbox.org/virtualbox/6.1.8/VBoxGuestAdditions_6.1.8.iso', 'C:\Windows\Temp\VBoxGuestAdditions.iso')
}
}
cmd /c ""C:\PROGRA~1\7-Zip\7z.exe" x C:\Windows\Temp\VBoxGuestAdditions.iso -oC:\Windows\Temp\virtualbox"
Get-ChildItem "C:\Windows\Temp\virtualbox\cert\" -Filter vbox*.cer | Foreach-Object { C:\Windows\Temp\virtualbox\cert\VBoxCertUtil add-trusted-publisher $_.FullName --root $_.FullName }
cmd /c C:\Windows\Temp\virtualbox\VBoxWindowsAdditions.exe /S
cmd /c rd /S /Q "C:\Windows\Temp\virtualbox"
}
if ("$env:PACKER_BUILDER_TYPE" -eq "parallels-iso") {
Write-Output "Using Parallels Desktop"
# This is required when using Parallels Desktop
# Currently the installation of Parallels Tools is broken if you're installing in Windows Server & Windows Server Core
# You will encounter an error in printui.dll module not found message.
# This feature will add the required libraries for printing services.
# Parallels Tools is required for sync_folder to work.
# Vagrantfile config: v.update_guest_tools = true will be installed with no issues
if ($(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ProductName.StartsWith("Windows Server")) {
Write-Output "Installing Print Server service"
Install-WindowsFeature -Name Print-Server
}
}
cmd /c msiexec /qb /x C:\Windows\Temp\7z1900-x64.msi

View File

@ -0,0 +1,260 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
param($global:RestartRequired = 0,
$global:MoreUpdates = 0,
$global:MaxCycles = 5,
$MaxUpdatesPerCycle = 500,
$BeginWithRestart = 0)
$Logfile = "C:\Windows\Temp\win-updates.log"
$enable_winrm_script = 'a:\enable-winrm.ps1'
if (test-path 'e:\enable-winrm.ps1') {
$enable_winrm_script = 'e:\enable-winrm.ps1'
}
function LogWrite {
Param ([string]$logstring)
$now = Get-Date -format s
Add-Content $Logfile -value "$now $logstring"
Write-Output $logstring
}
function Check-ContinueRestartOrEnd() {
$RegistryKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
$RegistryEntry = "InstallWindowsUpdates"
switch ($global:RestartRequired) {
0 {
$prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
if ($prop) {
LogWrite "Restart Registry Entry Exists - Removing It"
Remove-ItemProperty -Path $RegistryKey -Name $RegistryEntry -ErrorAction SilentlyContinue
}
LogWrite "No Restart Required"
Check-WindowsUpdates
if (($global:MoreUpdates -eq 1) -and ($script:Cycles -le $global:MaxCycles)) {
Install-WindowsUpdates
}
elseif ($script:Cycles -gt $global:MaxCycles) {
LogWrite "Exceeded Cycle Count - Stopping"
LogWrite "==> Running '$enable_winrm_script'..."
& $enable_winrm_script
}
else {
LogWrite "Done Installing Windows Updates"
LogWrite "==> Running '$enable_winrm_script'..."
& $enable_winrm_script
}
}
1 {
$prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
if (-not $prop) {
LogWrite "Restart Registry Entry Does Not Exist - Creating It"
Set-ItemProperty -Path $RegistryKey -Name $RegistryEntry -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File $($script:ScriptPath) -MaxUpdatesPerCycle $($MaxUpdatesPerCycle)"
}
else {
LogWrite "Restart Registry Entry Exists Already"
}
LogWrite "Restart Required - Restarting..."
Restart-Computer
}
default {
LogWrite "Unsure If A Restart Is Required"
break
}
}
}
function Install-WindowsUpdates()
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
param()
$script:Cycles++
LogWrite "Evaluating Available Updates with limit of $($MaxUpdatesPerCycle):"
$UpdatesToDownload = New-Object -ComObject 'Microsoft.Update.UpdateColl'
$script:i = 0;
$CurrentUpdates = $SearchResult.Updates
while ($script:i -lt $CurrentUpdates.Count -and $script:CycleUpdateCount -lt $MaxUpdatesPerCycle) {
$Update = $CurrentUpdates.Item($script:i)
if ($null -ne $Update) {
[bool]$addThisUpdate = $false
if ($Update.InstallationBehavior.CanRequestUserInput) {
LogWrite "> Skipping: $($Update.Title) because it requires user input"
}
else {
if (!($Update.EulaAccepted)) {
LogWrite "> Note: $($Update.Title) has a license agreement that must be accepted. Accepting the license."
$Update.AcceptEula()
[bool]$addThisUpdate = $true
$script:CycleUpdateCount++
}
else {
[bool]$addThisUpdate = $true
$script:CycleUpdateCount++
}
}
if ([bool]$addThisUpdate) {
LogWrite "Adding: $($Update.Title)"
$UpdatesToDownload.Add($Update) | Out-Null
}
}
$script:i++
}
if ($UpdatesToDownload.Count -eq 0) {
LogWrite "No Updates To Download..."
}
else {
LogWrite 'Downloading Updates...'
$ok = 0;
while (! $ok) {
try {
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $UpdatesToDownload
$Downloader.Download()
$ok = 1;
}
catch {
LogWrite $_.Exception | Format-List -force
LogWrite "Error downloading updates. Retrying in 30s."
$script:attempts = $script:attempts + 1
Start-Sleep -s 30
}
}
}
$UpdatesToInstall = New-Object -ComObject 'Microsoft.Update.UpdateColl'
[bool]$rebootMayBeRequired = $false
LogWrite 'The following updates are downloaded and ready to be installed:'
foreach ($Update in $SearchResult.Updates) {
if (($Update.IsDownloaded)) {
LogWrite "> $($Update.Title)"
$UpdatesToInstall.Add($Update) | Out-Null
if ($Update.InstallationBehavior.RebootBehavior -gt 0) {
[bool]$rebootMayBeRequired = $true
}
}
}
if ($UpdatesToInstall.Count -eq 0) {
LogWrite 'No updates available to install...'
$global:MoreUpdates = 0
$global:RestartRequired = 0
LogWrite "==> Running '$enable_winrm_script'..."
& $enable_winrm_script
break
}
if ($rebootMayBeRequired) {
LogWrite 'These updates may require a reboot'
$global:RestartRequired = 1
}
LogWrite 'Installing updates...'
$Installer = $script:UpdateSession.CreateUpdateInstaller()
$Installer.Updates = $UpdatesToInstall
$InstallationResult = $Installer.Install()
LogWrite "Installation Result: $($InstallationResult.ResultCode)"
LogWrite "Reboot Required: $($InstallationResult.RebootRequired)"
LogWrite 'Listing of updates installed and individual installation results:'
if ($InstallationResult.RebootRequired) {
$global:RestartRequired = 1
}
else {
$global:RestartRequired = 0
}
for ($i = 0; $i -lt $UpdatesToInstall.Count; $i++) {
New-Object -TypeName PSObject -Property @{
Title = $UpdatesToInstall.Item($i).Title
Result = $InstallationResult.GetUpdateResult($i).ResultCode
}
LogWrite "Item: $($UpdatesToInstall.Item($i).Title)"
LogWrite "Result: $($InstallationResult.GetUpdateResult($i).ResultCode)"
}
Check-ContinueRestartOrEnd
}
function Check-WindowsUpdates() {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
param()
LogWrite "Checking For Windows Updates"
$Username = $env:USERDOMAIN + "\" + $env:USERNAME
LogWrite "Script: $script:ScriptPath `nScript User: $Username `nStarted: $(Get-Date)"
$script:UpdateSearcher = $script:UpdateSession.CreateUpdateSearcher()
$script:successful = $FALSE
$script:attempts = 0
$script:maxAttempts = 12
while (-not $script:successful -and $script:attempts -lt $script:maxAttempts) {
try {
$script:SearchResult = $script:UpdateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
$script:successful = $TRUE
}
catch {
LogWrite $_.Exception | Format-List -force
LogWrite "Search call to UpdateSearcher was unsuccessful. Retrying in 10s."
$script:attempts = $script:attempts + 1
Start-Sleep -s 10
}
}
if ($SearchResult.Updates.Count -ne 0) {
$Message = "There are " + $SearchResult.Updates.Count + " more updates."
LogWrite $Message
try {
for ($i = 0; $i -lt $script:SearchResult.Updates.Count; $i++) {
LogWrite $script:SearchResult.Updates.Item($i).Title
LogWrite $script:SearchResult.Updates.Item($i).Description
LogWrite $script:SearchResult.Updates.Item($i).RebootRequired
LogWrite $script:SearchResult.Updates.Item($i).EulaAccepted
}
$global:MoreUpdates = 1
}
catch {
LogWrite $_.Exception | Format-List -force
LogWrite "Showing SearchResult was unsuccessful. Rebooting."
$global:RestartRequired = 1
$global:MoreUpdates = 0
Check-ContinueRestartOrEnd
LogWrite "Show never happen to see this text!"
Restart-Computer
}
}
else {
LogWrite 'There are no applicable updates'
$global:RestartRequired = 0
$global:MoreUpdates = 0
}
}
$script:ScriptName = $MyInvocation.MyCommand.ToString()
$script:ScriptPath = $MyInvocation.MyCommand.Path
$script:UpdateSession = New-Object -ComObject 'Microsoft.Update.Session'
$script:UpdateSession.ClientApplicationID = 'Packer Windows Update Installer'
$script:UpdateSearcher = $script:UpdateSession.CreateUpdateSearcher()
$script:SearchResult = New-Object -ComObject 'Microsoft.Update.UpdateColl'
$script:Cycles = 0
$script:CycleUpdateCount = 0
if ($BeginWithRestart) {
$global:RestartRequired = 1
Check-ContinueRestartOrEnd
}
Check-WindowsUpdates
if ($global:MoreUpdates -eq 1) {
Install-WindowsUpdates
}
else {
Check-ContinueRestartOrEnd
}