Skip to content

Instantly share code, notes, and snippets.

@tvjames
Last active August 11, 2022 14:27
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 25 You must be signed in to fork a gist
  • Save tvjames/6750255 to your computer and use it in GitHub Desktop.
Save tvjames/6750255 to your computer and use it in GitHub Desktop.
Prepare a Windows Server 2008 R2 instance for use with vagrant-windows.
# Powershell Script to prepare the windows install to be used with vagrant-windows
Set-ExecutionPolicy -executionpolicy remotesigned -force
# Step 1: Disable UAC
New-ItemProperty -Path HKLM:Software\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -PropertyType DWord -Value 0 -Force | Out-Null
Write-Host "User Access Control (UAC) has been disabled." -ForegroundColor Green
# Step 2: Disable IE ESC
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}" -Name "IsInstalled" -Value 0 | Out-Null
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}" -Name "IsInstalled" -Value 0 | Out-Null
Stop-Process -Name Explorer | Out-Null
Write-Host "IE Enhanced Security Configuration (ESC) has been disabled." -ForegroundColor Green
# Step 3: Disable the shutdown tracker
# Reference: http://www.askvg.com/how-to-disable-remove-annoying-shutdown-event-tracker-in-windows-server-2003-2008/
If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability")) {
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability"
}
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" -Name "ShutdownReasonOn" -PropertyType DWord -Value 0 -Force -ErrorAction continue
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" -Name "ShutdownReasonUI" -PropertyType DWord -Value 0 -Force -ErrorAction continue
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" -Name "ShutdownReasonOn" -Value 0
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" -Name "ShutdownReasonUI" -Value 0
Write-Host "Shutdown Tracker has been disabled." -ForegroundColor Green
# Step 4: Disable Automatic Updates
# Reference: http://www.benmorris.me/2012/05/1st-test-blog-post.html
$AutoUpdate = (New-Object -com "Microsoft.Update.AutoUpdate").Settings
$AutoUpdate.NotificationLevel = 1
$AutoUpdate.Save()
Write-Host "Windows Update has been disabled." -ForegroundColor Green
# Step 5: Disable Complex Passwords
# Reference: http://vlasenko.org/2011/04/27/removing-password-complexity-requirements-from-windows-server-2008-core/
$seccfg = [IO.Path]::GetTempFileName()
secedit /export /cfg $seccfg
(Get-Content $seccfg) | Foreach-Object {$_ -replace "PasswordComplexity\s*=\s*1", "PasswordComplexity=0"} | Set-Content $seccfg
secedit /configure /db $env:windir\security\new.sdb /cfg $seccfg /areas SECURITYPOLICY
del $seccfg
Write-Host "Complex Passwords have been disabled." -ForegroundColor Green
# Step 6: Enable Remote Desktop
# Reference: http://social.technet.microsoft.com/Forums/windowsserver/en-US/323d6bab-e3a9-4d9d-8fa8-dc4277be1729/enable-remote-desktop-connections-with-powershell
(Get-WmiObject Win32_TerminalServiceSetting -Namespace root\cimv2\TerminalServices).SetAllowTsConnections(1,1)
(Get-WmiObject -Class "Win32_TSGeneralSetting" -Namespace root\cimv2\TerminalServices -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0)
# Step 7: Enable WinRM Control
winrm quickconfig -q
winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="512"}'
winrm set winrm/config '@{MaxTimeoutms="1800000"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'
Write-Host "WinRM has been configured and enabled." -ForegroundColor Green
# Step 8: Disable Windows Firewall
&netsh "advfirewall" "set" "allprofiles" "state" "off"
Write-Host "Windows Firewall has been disabled." -ForegroundColor Green
# Step 9: Create local vagrant user
$userDirectory = [ADSI]"WinNT://localhost"
$user = $userDirectory.Create("User", "vagrant")
$user.SetPassword("vagrant")
$user.SetInfo()
$user.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD
$user.SetInfo()
$user.FullName = "vagrant"
$user.SetInfo()
&net "localgroup" "administrators" "/add" "vagrant"
Write-Host "User: 'vagrant' has been created as a local administrator." -ForegroundColor Green
# Install Puppet
$puppetTempDir = Join-Path $env:TEMP "puppet"
$tempDir = Join-Path $puppetTempDir "puppetInstall"
if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)}
$file = Join-Path $tempDir "puppet-3.3.0.msi"
$url = "http://downloads.puppetlabs.com/windows/puppet-3.3.0.msi"
Write-Host "Downloading $url to $file"
$downloader = new-object System.Net.WebClient
$downloader.DownloadFile($url, $file)
$localcommand="\\localhost\root\cimv2:Win32_Product"
$msi = [wmiclass]"$localcommand"
$result = $msi.Install($file, "quiet=true", $true)
Write-Host "Puppet installed." -ForegroundColor Green
$PuppetInstallPath = "$env:SystemDrive\Program Files (x86)\Puppet Labs\Puppet\bin"
if (!(Test-Path $PuppetInstallPath)) {$PuppetInstallPath = "$env:SystemDrive\Program Files\Puppet Labs\Puppet\bin";}
# get the PATH variable
# https://github.com/ferventcoder/vagrant-windows-puppet/blob/master/boxes/win7x64pro-vagrant/shell/InstallPuppet.ps1#L27-L40
$envPath = $env:PATH
if (!$envPath.ToLower().Contains($PuppetInstallPath.ToLower())) {
Write-Host "PATH environment variable does not have `'$PuppetInstallPath`' in it. Adding..."
$ActualPath = [Environment]::GetEnvironmentVariable('Path', [System.EnvironmentVariableTarget]::Machine)
$StatementTerminator = ";"
$HasStatementTerminator = $ActualPath -ne $null -and $ActualPath.EndsWith($StatementTerminator)
If (!$HasStatementTerminator -and $ActualPath -ne $null) {$PuppetInstallPath = $StatementTerminator + $PuppetInstallPath}
[Environment]::SetEnvironmentVariable('Path', $ActualPath + $PuppetInstallPath, [System.EnvironmentVariableTarget]::Machine)
}
Write-Host "Restarting Computer." -ForegroundColor Yellow
Restart-Computer
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# All Vagrant configuration is done here. The most common configuration
# options are documented and commented below. For a complete reference,
# please see the online documentation at vagrantup.com.
# Every Vagrant virtual environment requires a box to build off of.
config.vm.box = "windows-server-2008-r2-eval"
config.vm.guest = :windows
config.winrm.timeout = 500
# The url from where the 'config.vm.box' box will be fetched if it
# doesn't already exist on the user's system.
# config.vm.box_url = "http://domain.com/path/to/above.box"
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine. In the example below,
# accessing "localhost:8080" will access port 80 on the guest machine.
config.vm.network :forwarded_port, guest: 80, host: 8080
config.vm.network :forwarded_port, guest: 5985, host: 5985
config.vm.network :forwarded_port, guest: 1433, host: 1433
# Create a private network, which allows host-only access to the machine
# using a specific IP.
config.vm.network :private_network, ip: "192.168.33.11"
# Create a public network, which generally matched to bridged network.
# Bridged networks make the machine appear as another physical device on
# your network.
# config.vm.network :public_network
# If true, then any SSH connections made will enable agent forwarding.
# Default value: false
# config.ssh.forward_agent = true
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
# config.vm.synced_folder "../data", "/vagrant_data"
# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
#
config.vm.provider :virtualbox do |vb|
# Don't boot with headless mode
vb.gui = true
# Use VBoxManage to customize the VM. For example to change memory:
vb.customize ["modifyvm", :id, "--memory", "2048"]
end
#
# View the documentation for the provider you're using for more
# information on available options.
# Enable provisioning with Puppet stand alone. Puppet manifests
# are contained in a directory path relative to this Vagrantfile.
# You will need to create the manifests directory and a manifest in
# the file windows-server-2008-r2-eval.pp in the manifests_path directory.
#
# An example Puppet manifest to provision the message of the day:
#
# # group { "puppet":
# # ensure => "present",
# # }
# #
# # File { owner => 0, group => 0, mode => 0644 }
# #
# # file { '/etc/motd':
# # content => "Welcome to your Vagrant-built virtual machine!
# # Managed by Puppet.\n"
# # }
#
# config.vm.provision :puppet do |puppet|
# puppet.manifests_path = "manifests"
# puppet.manifest_file = "site.pp"
# end
# Enable provisioning with chef solo, specifying a cookbooks path, roles
# path, and data_bags path (all relative to this Vagrantfile), and adding
# some recipes and/or roles.
#
# config.vm.provision :chef_solo do |chef|
# chef.cookbooks_path = "../my-recipes/cookbooks"
# chef.roles_path = "../my-recipes/roles"
# chef.data_bags_path = "../my-recipes/data_bags"
# chef.add_recipe "mysql"
# chef.add_role "web"
#
# # You may also specify custom JSON attributes:
# chef.json = { :mysql_password => "foo" }
# end
# Enable provisioning with chef server, specifying the chef server URL,
# and the path to the validation key (relative to this Vagrantfile).
#
# The Opscode Platform uses HTTPS. Substitute your organization for
# ORGNAME in the URL and validation key.
#
# If you have your own Chef Server, use the appropriate URL, which may be
# HTTP instead of HTTPS depending on your configuration. Also change the
# validation key to validation.pem.
#
# config.vm.provision :chef_client do |chef|
# chef.chef_server_url = "https://api.opscode.com/organizations/ORGNAME"
# chef.validation_key_path = "ORGNAME-validator.pem"
# end
#
# If you're using the Opscode platform, your validator client is
# ORGNAME-validator, replacing ORGNAME with your organization name.
#
# If you have your own Chef Server, the default validation client name is
# chef-validator, unless you changed the configuration.
#
# chef.validation_client_name = "ORGNAME-validator"
end
#!/bin/bash
# Creates a VirtualBox VM capable of running the Windows Server 2008 R2 Evaluation VHD
# http://www.microsoft.com/en-au/download/details.aspx?id=16572
if [ ! -f "$1" ]; then
echo "Usage: `basename $0` source_vhd_file_path" >&2;
exit -1;
fi;
SOURCE_VHD=$1;
SOURCE=$(basename -s '.vhd' -a "${SOURCE_VHD}");
TARGET="${SOURCE}.$$";
TARGET_VHD="./${TARGET}.vhd";
echo "Copying $SOURCE_VHD to $TARGET_VHD";
cp -v "${SOURCE_VHD}" "${TARGET_VHD}";
echo "Creating VirtualBox VM to run target image"
VBoxManage createvm --name "${TARGET}" --register;
VBoxManage modifyvm "${TARGET}" --ostype Windows2008_64;
VBoxManage modifyvm "${TARGET}" --memory 2048 --vram 64 --cpus 2 --pae on --ioapic on --hwvirtex on --acpi on --boot1 disk;
VBoxManage modifyvm "${TARGET}" --nic1 nat --nictype1 82545EM;
VBoxManage modifyvm "${TARGET}" --audio none --usb on --usbehci on;
VBoxManage modifyvm "${TARGET}" --clipboard bidirectional --draganddrop disabled;
VBoxManage modifyvm "${TARGET}" --vrde off;
VBoxManage storagectl "${TARGET}" --name "IDE Controller" --add ide;
VBoxManage storageattach "${TARGET}" --storagectl "IDE Controller" --port 0 --device 0 --type hdd --medium "${TARGET_VHD}";
VBoxManage storageattach "${TARGET}" --storagectl "IDE Controller" --port 1 --device 0 --type dvddrive --medium emptydrive;
VBoxManage startvm "${TARGET}";
exit $?;
@pbrit
Copy link

pbrit commented Nov 18, 2013

VBoxManage modifyvm "${TARGET}" --audio none --usb on --usbehci on;

With snippet above VM can't load properly.

I got error like this:

VBoxManage: error: Implementation of the USB 2.0 controller not found!
VBoxManage: error: Because the USB 2.0 controller state is part of the saved VM state, the VM cannot be started. To fix this problem, either install the 'Oracle VM VirtualBox Extension Pack' or disable USB 2.0 support in the VM settings (VERR_NOT_FOUND)
VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component Console, interface IConsole

I commented the first line out and the VM started booting properly.

@lonniev
Copy link

lonniev commented Dec 11, 2014

The ps1 script is very helpful; thank you for taking the effort to script it so that the steps are recorded in one convenient place.

@lucianosousa
Copy link

it's possible to to this from a *nix system?

@faredigi
Copy link

@lucianosousa: it could be but there's better around if you (as I have to) plan to boot Windows from *nix. I personally found this https://github.com/joefitzgerald/packer-windows.git and this https://github.com/mwrock/boxstarter both very good (a bit better the first). Enjoy!

@dragon788
Copy link

Another good option is https://github.com/boxcutter/windows.git which has automated build capabilities and supports both evaluation and full versions from MSDN.

@mikexcel
Copy link

I'm assuming at some point in the process, the 'annoying security features' are renabled? Disabling IE Safe browsing, the firewall, and complex passwords are all bad things, in the long term. If removal is necessary to script the process, and they're re-enabled later on, then no big deal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment