Pages

fredag 14. juni 2013

Windows Server 2012: VM template tuning using PowerShell

This is a list of commands that I use when setting up a Windows Server 2012 Core template (can also be used for GUI template). I run all of these commands in PowerShell, either as a script or manually. In server core you start PowerShell by typing powershell.

I hope others will find this usefull. Please give me feedback if you have suggestions or improvements...

# Turn off 8dot3name
fsutil.exe 8dot3name set C: 1
fsutil.exe 8dot3name set 1

# Set Power plan to High performance
powercfg.exe /SETACTIVE 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c

# Disable the hibernate feature
powercfg.exe /HIBERNATE off

# Set Password Never Expires on the local Administrator account
gwmi Win32_UserAccount -Filter "name = 'Administrator'" | swmi -Arguments @{PasswordExpires = 0}

# Change Drive Letter on DVD Drive to X
gwmi Win32_Volume -Filter "DriveType = '5'" | swmi -Arguments @{DriveLetter = 'X:'}

# Initialize RAW disks
Get-Disk | Where-Object PartitionStyle –eq 'RAW' | Initialize-Disk –PartitionStyle MBR

# Format disk 0 for pagefile
# Verify correct disknumber before use
New-Partition –DiskNumber 0 -UseMaximumSize -AssignDriveLetter | Format-Volume -NewFileSystemLabel 'Pagefile' -FileSystem NTFS -AllocationUnitSize 65536 -Confirm:$false

# Disable Indexing on all drives
gwmi Win32_Volume -Filter "IndexingEnabled=$true" | swmi -Arguments @{IndexingEnabled=$false}

# Set location for dedicated dump file at system failure
# Verify correct path before use
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\CrashControl' -Name 'DedicatedDumpFile' -Value 'D:\MEMORY.DMP'
gwmi Win32_OSRecoveryConfiguration -EnableAllPrivileges | swmi -Arguments @{DebugFilePath='D:\MEMORY.DMP'}

# Use small memory dump at system failure
# 0=None, 1=Complete, 2=Kernel, 3=Small, 7=Automatic
gwmi Win32_OSRecoveryConfiguration -EnableAllPrivileges | swmi -Arguments @{DebugInfoType=3}

# Change setting to: Do not automatically restart at system failure
gwmi Win32_OSRecoveryConfiguration -EnableAllPrivileges | swmi -Arguments @{AutoReboot=$false}

# Turn off automatically manage paging file size for all drives
gwmi Win32_ComputerSystem -EnableAllPrivileges | swmi -Arguments @{AutomaticManagedPagefile=$false}

# Change paging file to the pagefile drive
# Verify correct location/name and size
# Get current paging file on drive C
$CurrentPageFile = gwmi -Query "select * from Win32_PageFileSetting where name='c:\\pagefile.sys'" -EnableAllPrivileges
# Delete current paging file on drive C
If($CurrentPageFile){$CurrentPageFile.Delete()}
# Create paging file on paging drive
swmi Win32_PageFileSetting -Arguments @{Name='D:\pagefile.sys'; InitialSize=2048; MaximumSize=2048}

# Allow all MMC snap-ins to connect from remote
Enable-NetFirewallRule -DisplayGroup 'Windows Remote Management'

# Enable Remote Desktop for Administration mode to accept connections
cscript C:\Windows\System32\Scregedit.wsf /ar 0

# Allow previous versions (XP/Win2003) of windows to connect
cscript C:\Windows\System32\Scregedit.wsf /cs 0

# Allow server response to Ping
netsh firewall set icmpsetting 8

# Verify time, date and timezone
control timedate.cpl

# Disable NetBIOS over TCP/IP - 2=disable, 1=enable, 0=DHCP default
# And WINS LMHOSTS lookup
# Verify correct ServiceName, for vmware use -like 'vmxnet*'
$nics = gwmi Win32_NetworkAdapterConfiguration | Where-Object {$_.ServiceName -eq 'netvsc'}
foreach ($nic in $nics) {
  If ($nic.TcpipNetbiosOptions -ne 2) {
    $nic.SetTcpipNetbios(2)
    # Turn off LMHOSTS lookup
    $nic.EnableWINS($false,$false)
  }
}

# Turn off DHCP on Ethernet Interface
# Verify InterfaceAlias
Set-NetIPInterface -InterfaceAlias Ethernet -Dhcp Disabled

# Set static IP on Ethernet Interface
# Verify IP address and Default Gateway
New-NetIPAddress -InterfaceAlias Ethernet -IPAddress 192.168.160.9 -DefaultGateway 192.168.160.5 -AddressFamily IPv4 -PrefixLength 24

# Set DNS server for Ethernet interface to Google and OpenDNS
Set-DnsClientServerAddress -InterfaceAlias Ethernet -ServerAddresses ('8.8.8.8', '208.67.222.222')

# Install Windows Updates, reboot and repeat until no updates exist - alternative is to use sconfig
cscript c:\Windows\System32\en-US\WUA_SearchDownloadInstall.vbs

# Install WMI hotfix for WS2012 KB2790831
# Verify correct location for downloading the hotfix - using dropbox in this example (link is modified)
$WebClient = New-Object Net.WebClient
$WebClient.DownloadFile("https://dl.dropboxusercontent.com/u/123456789/Windows8-RT-KB2790831-x64.msu","C:\Users\Administrator\Downloads\Windows8-RT-KB2790831-x64.msu")
& C:\Users\Administrator\Downloads\Windows8-RT-KB2790831-x64.msu
del C:\Users\Administrator\Downloads\Windows8-RT-KB2790831-x64.msu

# For Hyper-V VM update integration services (insert Integration Services Setup Disk in Hyper-V Manager)
D:\support\amd64\setup.exe

# Allow blank password on Administrator account (change to blank password - only for the template - using Ctrl-Alt-Del screen)
$Signature='"$CHICAGO$"'
Write-Output "[System Access]`r`nPasswordComplexity = 0`r`n[Version]`r`nsignature=$Signature`r`nRevision=1" | Out-File -FilePath "C:\Users\Administrator\local.cfg" -Encoding unicode
secedit /configure /db C:\Windows\security\local.sdb /cfg C:\Users\Administrator\local.cfg /areas SECURITYPOLICY
del C:\Users\Administrator\local.cfg

# Remove all windows features not used:
# To install a removed feature later, insert windows media and use (example for Web-Server):
# Install-WindowsFeature Web-Server -Source:wim:X:\Sources\install.wim:1
Get-WindowsFeature | Where-Object {$_.InstallState -eq 'Available'} | Uninstall-WindowsFeature -Remove
# Or you can remove only selected features:
Uninstall-WindowsFeature -Remove -Name WINS,Migration,RSAT,MSMQ,Server-Media-Foundation,GPMC,BitLocker,Hyper-V,Subsystem-UNIX-Apps,qWave

# Start Disk Optimization and Defrag all disks
Get-Volume | Where-Object {$_.DriveType -eq 'Fixed'} | Optimize-Volume -Defrag

# Zero out free space with SDelete (download it and copy to C:\Windows\System32)
sdelete -z c: -accepteula

# Remove static IP before creating a template from this VM
$Adapter = Get-NetAdapter -Name Ethernet
$Adapter | Set-NetIPInterface -Dhcp Enabled
Remove-NetRoute -InterfaceAlias $Adapter.Name -Confirm:$false
ipconfig /release

For SCVMM:
As a last step shutdown VM and use compact disk before clone and create template.
When I create a template I often use a custom unattend.xml - example for Core template:
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
  <settings pass="generalize">
    <component language="neutral" name="Microsoft-Windows-PnpSysprep" processorarchitecture="amd64" publickeytoken="31bf3856ad364e35" versionscope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <persistalldeviceinstalls>true</persistalldeviceinstalls>
    </component>
  </settings>
  <settings pass="oobeSystem">
    <component language="neutral" name="Microsoft-Windows-Shell-Setup" processorarchitecture="amd64" publickeytoken="31bf3856ad364e35" versionscope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <oobe>
        <hideeulapage>true</hideeulapage>
        <protectyourpc>3</protectyourpc>
        <networklocation>Work</networklocation>
        <hidewirelesssetupinoobe>true</hidewirelesssetupinoobe>
        <hidelocalaccountscreen>true</hidelocalaccountscreen>
        <hideonlineaccountscreens>true</hideonlineaccountscreens>
        <hideoemregistrationscreen>true</hideoemregistrationscreen>
      </oobe>
      <registeredorganization>Contoso</registeredorganization>
      <registeredowner>Admin User</registeredowner>
      <timezone>W. Europe Standard Time</timezone>
    </component>
    <component language="neutral" name="Microsoft-Windows-International-Core" processorarchitecture="amd64" publickeytoken="31bf3856ad364e35" versionscope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <inputlocale>0409:00000414</inputlocale>
      <systemlocale>en-US</systemlocale>
      <uilanguage>en-US</uilanguage>
      <userlocale>en-US</userlocale>
      <uilanguagefallback>en-US</uilanguagefallback>
    </component>
  </settings>
  <settings pass="specialize">
    <component language="neutral" name="Microsoft-Windows-ErrorReportingCore" processorarchitecture="amd64" publickeytoken="31bf3856ad364e35" versionscope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <disablewer>1</disablewer>
    </component>
    <component language="neutral" name="Microsoft-Windows-TerminalServices-LocalSessionManager" processorarchitecture="amd64" publickeytoken="31bf3856ad364e35" versionscope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <fdenytsconnections>false</fdenytsconnections>
    </component>
    <component language="neutral" name="Networking-MPSSVC-Svc" processorarchitecture="amd64" publickeytoken="31bf3856ad364e35" versionscope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <firewallgroups>
        <firewallgroup wcm:action="add" wcm:keyvalue="RemoteDesktop">
          <active>true</active>
          <group>Remote Desktop</group>
          <profile>all</profile>
        </firewallgroup>
      </firewallgroups>
    </component>
    <component language="neutral" name="Microsoft-Windows-TerminalServices-RDP-WinStationExtensions" processorarchitecture="amd64" publickeytoken="31bf3856ad364e35" versionscope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <userauthentication>0</userauthentication>
    </component>
    <component language="neutral" name="Microsoft-Windows-Shell-Setup" processorarchitecture="amd64" publickeytoken="31bf3856ad364e35" versionscope="NonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <timezone>W. Europe Standard Time</timezone>
      <registeredorganization>Contoso</registeredorganization>
      <registeredowner>Admin User</registeredowner>
    </component>
    <component language="neutral" name="Microsoft-Windows-Deployment" processorarchitecture="amd64" publickeytoken="31bf3856ad364e35" versionscope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <runsynchronous>
        <runsynchronouscommand wcm:action="add">
          <order>1</order>
          <path>cmd /c reg add "HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" /v ExecutionPolicy /t REG_SZ /d RemoteSigned /f</path>
          <description>Configure Powershell security settings</description>
        </runsynchronouscommand>
      </runsynchronous>
    </component>
    <component language="neutral" name="Microsoft-Windows-SQMApi" processorarchitecture="amd64" publickeytoken="31bf3856ad364e35" versionscope="NonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <ceipenabled>0</ceipenabled>
    </component>
  </settings>
</unattend>

And another example for a GUI:
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
  <settings pass="generalize">
    <component name="Microsoft-Windows-PnpSysprep" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <PersistAllDeviceInstalls>true</PersistAllDeviceInstalls>
    </component>
  </settings>
  <settings pass="oobeSystem">
    <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <VisualEffects>
        <FontSmoothing>ClearType</FontSmoothing>
        <SystemDefaultBackgroundColor>24</SystemDefaultBackgroundColor>
      </VisualEffects>
      <OOBE>
        <HideEULAPage>true</HideEULAPage>
        <ProtectYourPC>3</ProtectYourPC>
        <NetworkLocation>Work</NetworkLocation>
        <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
        <HideLocalAccountScreen>true</HideLocalAccountScreen>
        <HideOnlineAccountScreens>true</HideOnlineAccountScreens>
        <HideOEMRegistrationScreen>true</HideOEMRegistrationScreen>
      </OOBE>
      <WindowsFeatures>
        <ShowMediaCenter>false</ShowMediaCenter>
        <ShowWindowsMediaPlayer>false</ShowWindowsMediaPlayer>
      </WindowsFeatures>
      <RegisteredOrganization>Contoso</RegisteredOrganization>
      <RegisteredOwner>Admin User</RegisteredOwner>
      <TimeZone>W. Europe Standard Time</TimeZone>
    </component>
    <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <InputLocale>0409:00000414</InputLocale>
      <SystemLocale>en-US</SystemLocale>
      <UILanguage>en-US</UILanguage>
      <UserLocale>en-US</UserLocale>
      <UILanguageFallback>en-US</UILanguageFallback>
    </component>
  </settings>
  <settings pass="specialize">
    <component name="Microsoft-Windows-ErrorReportingCore" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <DisableWER>1</DisableWER>
    </component>
    <component name="Microsoft-Windows-IE-ESC" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <IEHardenAdmin>false</IEHardenAdmin>
      <IEHardenUser>false</IEHardenUser>
    </component>
    <component name="Microsoft-Windows-IE-InternetExplorer" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <DisableOOBAccelerators>true</DisableOOBAccelerators>
      <DisableFirstRunWizard>true</DisableFirstRunWizard>
      <DisableAccelerators>true</DisableAccelerators>
      <Home_Page>about:blank</Home_Page>
      <DisableDevTools>true</DisableDevTools>
      <DisableDataExecutionPrevention>false</DisableDataExecutionPrevention>
      <BlockPopups>no</BlockPopups>
      <SuggestedSitesEnabled>false</SuggestedSitesEnabled>
    </component>
    <component name="Microsoft-Windows-TerminalServices-LocalSessionManager" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <fDenyTSConnections>false</fDenyTSConnections>
    </component>
    <component name="Networking-MPSSVC-Svc" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <FirewallGroups>
        <FirewallGroup wcm:action="add" wcm:keyValue="RemoteDesktop">
          <Active>true</Active>
          <Group>Remote Desktop</Group>
          <Profile>all</Profile>
        </FirewallGroup>
      </FirewallGroups>
    </component>
    <component name="Microsoft-Windows-TerminalServices-RDP-WinStationExtensions" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <UserAuthentication>0</UserAuthentication>
    </component>
    <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="NonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <TimeZone>W. Europe Standard Time</TimeZone>
      <RegisteredOrganization>Contoso</RegisteredOrganization>
      <RegisteredOwner>Admin User</RegisteredOwner>
      <Themes>
        <WindowColor>Color 1</WindowColor>
      </Themes>
    </component>
    <component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <RunSynchronous>
        <RunSynchronousCommand wcm:action="add">
          <Order>1</Order>
          <Path>cmd /c reg add &quot;HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell&quot; /v ExecutionPolicy /t REG_SZ /d RemoteSigned /f</Path>
          <Description>Configure Powershell security settings</Description>
        </RunSynchronousCommand>
      </RunSynchronous>
    </component>
    <component name="Microsoft-Windows-SQMApi" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="NonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <CEIPEnabled>0</CEIPEnabled>
    </component>
    <component name="Microsoft-Windows-ServerManager-SvrMgrNc" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <DoNotOpenServerManagerAtLogon>true</DoNotOpenServerManagerAtLogon>
    </component>
  </settings>
</unattend>