Initialize a New Server

So I was given a task to set up about 20 servers in a limited amount of time, for this case I had to create a script which sets the server to the settings provided without making any changes to the group policies or domain settings.

Here below I change alot of windows parameters by functions:

You might find somehting usefull here :)


# Initialize Server
# By Lennar Kivistik
# 2014 # ## $cfg = @{ log_path = 'C:\Scripts\Logs\initial\' script = "C:\Scripts\initializeserver.ps1" external_file_server = '\\The-File-Server\initialserverfiles\*' download_file_path = 'c:\Scripts\Downloads\' script_task_name = 'InitializeInstallation' } $cfg += @{ installationprocessfile = $cfg['log_path']+"progress.txt" log_name = 'Server-Prep.log' } Function Log-Write { <# .SYNOPSIS This function will let you log to file. .DESCRIPTION This function will let you create and add log entries to a log file. .EXAMPLE .\Log-Write -Value 'My custom log Entry' -Name 'My Custom Log Name' -Path 'H:\My_Custom_Log_Path\' In this example H:\My_Custom_Log_Path\ would get a new Log file named 'My Custom Log Name' with the content of Value timestamped. #> Param ( [string]$Value="test", [string]$Name=$cfg['log_name'], [string]$LogPath=$cfg['log_path'], [switch]$NoDate=$False ) $Logfile = "$LogPath$(get-date -Format ('yyyy-MM-dd')) - $Name" if ($NoDate -eq $False) { $Value = $(get-date -Format ('yyyy-MM-dd HH:mm:ss')) + " - $Value" } if (!(Test-Path $Logfile)) { $NULL = New-Item $Logfile -type file -Force } Add-content $Logfile -value $Value Write-Output $Value } Function Get-InstallationProcess { Param ( [string]$File = $cfg['installationprocessfile'] ) if(!(Test-Path $File)) { New-Item -Path $File -ItemType File -Force -ErrorAction Stop Log-Write "No Inital installation process started" Set-Content $File -Value "0" Return "0" } else { Return Get-Content $File } } Function Set-InstallationProcess { Param( [string]$File=$cfg['installationprocessfile'], [string]$Value ) Set-Content $File -Value $Value -ErrorAction Stop } Function Disable-IEESC { $AdminKey = “HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}” $UserKey = “HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}” Set-ItemProperty -Path $AdminKey -Name “IsInstalled” -Value 0 Set-ItemProperty -Path $UserKey -Name “IsInstalled” -Value 0 #Stop-Process -Name Explorer Log-Write “ie enhanced security configuration (IE ESC) has been disabled.” } Function Set-Language { $locale = @{"Locale"="00000409"; "LocaleName"="sv-SE"; "s1159"=""; "s2359"="";"sCountry"="Sweden"; "sCurrency"="kr"; "sDate"="-"; "sDecimal"=",";"sGrouping"="3;0"; "sLanguage"="SVE"; "sList"=";"; "sLongDate"="'den 'd MMMM yyyy";"sMonDecimalSep"=","; "sMonGrouping"="3;0"; "sMonThousandSep"="."; "sNativeDigits"="0123456789";"sNegativeSign"="-"; "sPositiveSign"=""; "sShortDate"="yyyy-MM-dd"; "sThousand"=" ";"sTime"=":"; "sTimeFormat"="HH:mm:ss"; "sShortTime"="HH:mm"; "sYearMonth"="MMMM yyyy";"iCalendarType"="1"; "iCountry"="46"; "iCurrDigits"="2"; "iCurrency"="3"; "iDate"="2";"iDigits"="2"; "NumShape"="1"; "iFirstDayOfWeek"="0"; "iFirstWeekOfYear"="2"; "iLZero"="1";"iMeasure"="0"; "iNegCurr"="8"; "iNegNumber"="1"; "iPaperSize"="9"; "iTime"="1"; "iTimePrefix"="0"; "iTLZero"="1";} $locale.GetEnumerator() | % { Set-ItemProperty -Path "HKCU:\Control Panel\International" -Name $_.key -Value $_.value } Set-ItemProperty -Path "HKCU:\Control Panel\International\Geo" -Name "Nation" -Value '221' Log-Write "language set to swedish." } Function Set-TimeZone { $Null = Invoke-Expression 'tzutil /s "W. Europe Standard Time"' Log-Write "timezone set to: W. Europe Standard Time." } Function Disable-Firewall { Invoke-Expression "netsh advfirewall set allprofiles state off" Log-Write "windows firewall has been disabled." } Function Set-AudioService { Set-Service AudioSrv -startuptype "Automatic" Start-Service AudioSrv Log-Write "windows audio is set to automatic and has been started." } Function Set-WindowsUpdate { # Notification Level 1 is ~Never check for updates~ # Notification Level 2 is ~Check for updates but let me choose whether to download and install them~ # Notification Level 3 is ~Download updates but let me choose whether to install them~ # Notification Level 4 is ~Install updates automatically~ $objAutoUpdate =New-Object -ComObject "Microsoft.Update.AutoUpdate" $objSett = $objAutoUpdate.Settings $objSett.NotificationLevel = "3" $objSett.Save() Log-Write "windows update set to: download updates but let me choose whether to install them." } Function Download-Files { <# .SYNOPSIS Downloads the installationfiles to the localmachine. .DESCRIPTION Downloads Specified Files to the local machine. .EXAMPLE .\Download-Files -Path -Destination C:\Scripts\Downloads\ #> Param( [string]$Path=$cfg['external_file_server'], [string]$Destination=$cfg['download_file_path'] ) if (!(Test-Path $Destination)) { $NULL = New-Item $Destination -type directory -Force -ErrorAction Stop } If((Test-Path $Path)) { Log-Write "download started from: $Path" Copy-Item -Path $Path -Destination $Destination -Force -ErrorAction Stop -Recurse Log-Write "download completed to: $Destination" } } Function Set-NvidiaTCC { $File = "C:\Program Files\NVIDIA Corporation\NVSMI\nvidia-smi.exe" if((Test-Path $File)) { $TCC = Invoke-Expression "& '$File' -i 0 -fdm 1" if($TCC -match "Error") { Log-Write "*** ERROR - $TCC" } else { Log-Write "*** SUCCESS $TCC" } } else { Log-Write "ERROR *** nvidia-smi.exe not found / installed!" #Exit; } } Function Unblock-Files { Param( [array]$Paths = @($cfg['download_file_path'], "$($cfg['download_file_path'])dx10") ) foreach ($Path in $Paths) { & cmd.exe /c "dir `"$Path`" /r && exit 0 || exit 1" | Where { $_ -match "Zone.Identifier" } | ForEach-Object ` { $filename = $_.trimstart(' ').trimstart('1234567890').trimstart(' ').trimend(':$DATA') Log-Write "*** ZONE FILE Detected: $filename, trying to remove zone info." & cmd.exe /c "echo.>`"$($Path)$filename`" && exit 0 || exit 1"; } } } Function Install-Application { <# .SYNOPSIS This function will install an application specified. .DESCRIPTION This function will install a given application on the localhost, the user has to be administrator on the computer and powershell has to be run in elevated mode. .EXAMPLE .\Install-Application WHATEVER.exe -Arg '/quiet /silent /repair' This example would install "WHATEVER.exe" in quiet mode and repair etc.. #> Param( [Parameter(Mandatory=$True)][string]$Application, [string]$Arg='/s /v /qb', [switch]$NoRunAs=$FALSE ) if(Test-Path $Application) { $applicationinfo = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($Application) Log-Write "installing $($applicationinfo.ProductName) version: $($applicationinfo.ProductVersion)" if (($NoRunAs)) { $setup=Start-Process $Application -ArgumentList $Arg -Wait -PassThru } else { $setup=Start-Process $Application -ArgumentList $Arg -Wait -PassThru -Verb RunAs } if ($setup.exitcode -eq 0) { Log-Write "successfully installed $($applicationinfo.ProductName)!" } else { echo $setup.exitcode Log-Write "installation failed with exitcode: $($setup.exitcode) for: $($applicationinfo.ProductName)!" } } else { Log-Write "note *** application '$Application' can't be found, please check. exiting." exit; } } Function Create-ScheduledTask { param( [string]$ComputerName = "localhost", [string]$RunAsUser = "$($env:computername)\administrator", #System [string]$Password = "###########", [string]$TaskName = "blank", [string]$TaskRun = "'PowerShell.exe -NoLogo -File C:\Script\InitializeServer.ps1'", [string]$Schedule = "ONSTART" # MINUTE, HOURLY, DAILY, WEEKLY, MONTHLY, ONCE, ONSTART, ONLOGON, ONIDLE. ) $Command = "schtasks.exe /create /s $ComputerName /ru $RunAsUser /rp $Password /tn $TaskName /tr $TaskRun /sc $Schedule /F /rl HIGHEST" Invoke-Expression $Command Log-Write "task: $TaskName has been created on $ComputerName" } Function Get-ScheduledTask { param([string]$ComputerName = "localhost") Write-Host "Computer: $ComputerName" $Command = "schtasks.exe /query /s $ComputerName" Invoke-Expression $Command Clear-Variable Command -ErrorAction SilentlyContinue Write-Host "`n" } Function Remove-ScheduledTask { param( [string]$ComputerName = "localhost", [string]$TaskName = "blank" ) If ((Get-ScheduledTask -ComputerName $ComputerName) -match $TaskName) { $Command = "schtasks.exe /delete /s $ComputerName /tn $TaskName /F" Invoke-Expression $Command Clear-Variable Command -ErrorAction SilentlyContinue Log-Write "task: $TaskName has been removed on $ComputerName" } Else { Log-Write "task: $TaskName was not found on $ComputerName" } } $Progress = Get-InstallationProcess if($Progress -like "0") { Log-Write "starting new installation!" } switch ($Progress) { 0 { Create-ScheduledTask -TaskName $cfg['script_task_name'] Set-Language Set-TimeZone Disable-Firewall Disable-IEESC Set-AudioService Set-WindowsUpdate Download-Files Unblock-Files # Install DirectX10 Install-Application "$($cfg['download_file_path'])dx10\DXSETUP.exe" -Arg "/silent" # Microsoft Visual C++ 2012 Redistributable Install-Application "$($cfg['download_file_path'])vcredist_x86.exe" -Arg '/q /norestart' # dotNET451 Install-Application "$($cfg['download_file_path'])NET451.exe" -Arg "/q /norestart" Set-InstallationProcess -Value "1" Log-Write "restarting server... *** BIOS *** Change Videocard - External as Primary ***" Restart-Computer -Force } 1 { Set-NvidiaTCC Set-InstallationProcess -Value "2" Restart-Computer -Force } 2 { Remove-ScheduledTask -TaskName $cfg['script_task_name'] Log-Write "installation complete!" Log-Write "-------------------------------------------------------------------------" -NoDate } default { Log-Write "Progress Could not be determined!"} }


Posted on: Friday 23 January 2015