My first steps on Powershell
Ok, Ok, as an “Oracle on Linux Certified Expert”, I’ve never been a great fan of SQLServer (I shouldn’t say this, I’m working on SQLServer since release 6.5…) and I’ve always hated the DOS command prompt.
However, things are changing fast after Microsoft released the Powershell some years ago. It’s surprising, now Windows powershell support new best of breed features like aliases and pipelines. 😀
Today Microsoft itself recommends Windows Core installations instead of the full ones, and also SQLServer 2012 comes with a lot of new Commandlets to manage your server.
So I’ve decided to move my first steps in the Powershell world and I’ve created a script for a customer that installs and configure a SQL2008 with a single Powershell script.
It has been quite painful to complete, you can download the complete script HERE.
Taking parameters
The very first line accepts named parameters. I’ve tried to reduce the number but I’ve preferred to take, as an example, different disks for different tasks.
1 |
param ([string] $instance, [string] $collation, $ServiceAccountPassword, $saPassword, $sourceDir, $servicePackExec, $instDrive, $userDbDrive, $userLogDrive, $tempDbDrive, $tempLogDrive, $backupDrive , $port ) |
Then I’ve put a little of interaction if some parameters are missing. In facts, I can launch my scripts without inline parameters and specify everything when prompted by the script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
###################### # Getting Parameters # ###################### if ( -not $sourceDir) { $sourceDir = Read-Host 'Source Path containing SQL2008R2 installation ? ' } if ( -not $servicePackExec) { $servicePackExec = Read-Host 'Full Path to service pack executable [Empty for None]? ' } if ( -not $instance) { $instance = Read-Host 'Instance Name? ' } if ( -not $collation ) {$collation = Read-Host 'Collation [Latin1_General_CI_AS]? ' } if ( -not $collation ) { $collation = "Latin1_General_CI_AS" } if ( -not $port ) { $port = Read-Host 'TCP Port [50000]? ' } if ( -not $port ) { $port = "50000" } if ( -not $ServiceAccountPassword ) { [System.Security.SecureString]$ServiceAccountPassword = Read-Host "Enter the service account password: " -AsSecureString; [String]$syncSvcAccountPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($ServiceAccountPassword)); } else { [String]$syncSvcAccountPassword = $ServiceAccountPassword; } if ( -not $saPassword ) { [System.Security.SecureString]$saPasswordSec = Read-Host "Enter the sa password: " -AsSecureString; [String]$saPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($saPasswordSec)); } else { [String]$saPassword = $ServiceAccountPassword; } $instance = $instance.ToUpper() |
Before I prompt for the drive letters for the installation paths, I display a little table with the available local disks:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
function displayDrives () { Get-WmiObject -class "Win32_LogicalDisk" | ?{ @(2, 3) -contains $_.DriveType } | where {$_.Freespace} | select Name, VolumeName, Size, FreeSpace } ######################## # Getting Disk Letters # ######################## $driveDisplayed=0 if ( -not $instDrive ) { if ( $driveDisplayed -eq 0 ) { displayDrives ; $driveDisplayed=1 } $instDrive = Read-Host 'Drive letter (without colon) for Instance Installation? ' } if ( -not $userDbDrive ) { if ( $driveDisplayed -eq 0 ) { displayDrives ; $driveDisplayed=1 } $userDbDrive = Read-Host 'Drive letter (without colon) for User Databases? ' } if ( -not $userLogDrive ) { if ( $driveDisplayed -eq 0 ) { displayDrives ; $driveDisplayed=1 } $userLogDrive = Read-Host 'Drive letter (without colon) for Transaction Logs ? ' } if ( -not $tempDbDrive ) { if ( $driveDisplayed -eq 0 ) { displayDrives ; $driveDisplayed=1 } $tempDbDrive = Read-Host 'Drive letter (without colon) for Temp Database ? ' } if ( -not $tempLogDrive ) { if ( $driveDisplayed -eq 0 ) { displayDrives ; $driveDisplayed=1 } $tempLogDrive = Read-Host 'Drive letter (without colon) for Temp Logs ? ' } if ( -not $backupDrive ) { if ( $driveDisplayed -eq 0 ) { displayDrives ; $driveDisplayed=1 } $backupDrive = Read-Host 'Drive letter (without colon) for Backups ? ' } |
Installing prerequisites
1 2 3 4 5 6 7 8 9 10 11 12 13 |
############################### # install prerequisites for SQL2008R2 function installPrereqs () { Import-Module ServerManager Add-WindowsFeature Application-Server,AS-NET-Framework,NET-Framework,NET-Framework-Core,WAS,WAS-Process-Model,WAS-NET-Environment,WAS-Config-APIs # get-windowsfeature | Where {$_.Installed} | Sort FeatureType,Parent,Name | Select Name,Displayname,FeatureType,Parent } ###################### # Installing Prereqs # ###################### "Installing Prerequisites (.Net, etc) ..." installPrereqs |
The commented command is to get the installed features after the installation. No really need to display it, it works really well.
Dynamically prepare a configuration file
The unattended installation needs some parameters prepared in a configuration file.
This is likely where you will change most of your stuff depending on your standards:
Components, paths, service accounts, you can change everything or modify the script to accept also this variables as parameters.
The full documentation about filling the configuration file is on the MSDN:
http://msdn.microsoft.com/en-us/library/ms144259%28v=sql.105%29.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
######################################### # prepare the standard configuration file function prepareConfigFile ([String]$instance, [String]$collation, $instDrive, $userDbDrive, $userLogDrive, $tempDbDrive, $tempLogDrive, $backupDrive ) { $config = "[SQLSERVER2008] ACTION=""Install"" FEATURES=SQLENGINE,REPLICATION,FULLTEXT,BIDS,CONN,IS,BC,BOL,SSMS,ADV_SSMS,SNAC_SDK INSTANCENAME=""$instance"" INSTANCEID=""$instance"" INSTALLSHAREDDIR=""C:\Program Files\Microsoft SQL Server"" INSTALLSHAREDWOWDIR=""C:\Program Files (x86)\Microsoft SQL Server"" INSTANCEDIR=""C:\Program Files\Microsoft SQL Server"" INSTALLSQLDATADIR="""+$instDrive+":\MSSQL\$instance"" SQLUSERDBDIR="""+$userDbDrive+":\MSSQL\$instance\MSSQL10_50."+$instance+"\MSSQL\Data"" SQLUSERDBLOGDIR="""+$userLogDrive+":\MSSQL\$instance\MSSQL10_50."+$instance+"\MSSQL\Tlog"" SQLTEMPDBDIR="""+$tempDbDrive+":\MSSQL\$instance\MSSQL10_50."+$instance+"\MSSQL\Data"" SQLTEMPDBLOGDIR="""+$tempLogDrive+":\MSSQL\$instance\MSSQL10_50."+$instance+"\MSSQL\Tlog"" SQLBACKUPDIR="""+$backupDrive+":\MSSQL\$instance\MSSQL10_50."+$instance+"\MSSQL\Backup"" FILESTREAMLEVEL=""0"" TCPENABLED=""1"" NPENABLED=""1"" SQLCOLLATION=""$collation"" SQLSVCACCOUNT=""MYDOM\sqlsrvc"" SQLSVCSTARTUPTYPE=""Automatic"" AGTSVCACCOUNT=""MYDOM\sqlsrvc"" AGTSVCSTARTUPTYPE=""Automatic"" ISSVCACCOUNT=""NT AUTHORITY\NetworkService"" ISSVCSTARTUPTYPE=""Automatic"" BROWSERSVCSTARTUPTYPE=""Automatic"" SQLSYSADMINACCOUNTS=""MYDOM\sqlsrvc"" SECURITYMODE=""SQL"" SQMREPORTING=""False"" IACCEPTSQLSERVERLICENSETERMS=""True""" $config } ##################### # Creating Ini File # ##################### $workDir = pwd "Creating Ini File for Installation..." $configFile = "$workDir\sql2008_"+$instance+"_install.ini" prepareConfigFile $instance $collation $instDrive $userDbDrive $userLogDrive $tempDbDrive $tempLogDrive $backupDrive | Out-File $configFile "Configuration File written to: "+$configFile |
Starting the SQL Server 2008 R2 installation
Off course you’ll need an installation media downloaded from the Microsoft customers site with the correct License Keys and mounted somewhere. (remember the $sourceDir parameter?) I’ve decided to change the path in the directory containing the media and then change it back.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
####################################### # Starting SQL 2008 Base Installation # ####################################### set-location $sourceDir "Starting SQL 2008 Base Installation..." $installCmd = ".\setup.exe /qs /SQLSVCPASSWORD=""$syncSvcAccountPassword"" /AGTSVCPASSWORD=""$syncSvcAccountPassword"" /SAPWD=""$saPassword"" /ConfigurationFile=""$configFile""" $installCmd Invoke-Expression $installCmd set-location $workDir |
Launching the Service Pack installation
The Service Pack installation has been a little more painful, normally would be simple but actually the powershell prompt is returned immediately after firing the command. So, to wait it, I’ve had to figure out the name of the process (is the executable name without the file extension .exe), get its process id and wait for that process:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
####################################### # Starting SQL 2008 SP Installation # ####################################### if ( $servicePackExec) { "Starting Service Pack Installation..." $patchCmd = "$servicePackExec /Action=Patch /Quiet /IAcceptSQLServerLicenseTerms /Instancename=""$Instance""" $patchCmd Invoke-Expression $patchCmd ## have to take the name of the process and wait for the completion of the pid because service packs ## return prompt immediately and then run in background $process=[System.IO.Path]::GetFileNameWithoutExtension($servicePackExec) $nid = (Get-Process $process).id Wait-Process -id $nid } |
Changing the TCP port
By default SQLServer starts listening on a dynamic port. If you have a default and you want to configure it without opening the configuration manager, you can do it with this snipplet that I’ve copied from sirSql (thank you for sharing this).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
############################### # change the TCP port at the end of the installation function changePort ($SQLName , $Instance, $port) { Try { $SQLName $Instance # Load SMO Wmi.ManagedComputer assembly [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | out-null Trap { $err = $_.Exception while ( $err.InnerException ) { $err = $err.InnerException write-output $err.Message } continue } # Connect to the instance using SMO $m = New-Object ('Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer') $SQLName $urn = "ManagedComputer[@Name='$SQLName']/ServerInstance[@Name='$Instance']/ServerProtocol[@Name='Tcp']" $Tcp = $m.GetSmoObject($urn) $Enabled = $Tcp.IsEnabled #Enable TCP/IP if not enabled IF (!$Enabled) {$Tcp.IsEnabled = $true } #Set to listen on 50000 and disable dynamic ports $m.GetSmoObject($urn + "/IPAddress[@Name='IPAll']").IPAddressProperties[1].Value = $port $m.GetSmoObject($urn + "/IPAddress[@Name='IPAll']").IPAddressProperties['TcpDynamicPorts'].Value = '' $TCP.alter() "Success: SQL set to listen on TCP/IP port $port. Please restart the SQL service for changes to take effect." } Catch { Write-Warning "Unable to enable TCP/IP & set SQL to listen on port $port" } } #################### # Changing TCPport # #################### "Changing TCP port to $port..." changePort $hostName $instance $port |
Adding your stuff at the end
Having the installation completed is in midstream. After the installation you may want to add tempfiles to your installation, modify your model database, add default accounts.
That’s up to you. If your scripts are identical you can execute them with sqlcmd.If you want to take benefit of the variables already set in the script you can execute them directly:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
############################### # Resizing / Adding Tempfiles # ############################### $Connection = New-Object System.Data.SQLClient.SQLConnection $hostName = get-content env:computername $Connection.ConnectionString ="Server=$hostName\$instance;Database=master;uid=sa;Pwd=$saPassword;" $Connection.Open() $Command = New-Object System.Data.SQLClient.SQLCommand $Command.Connection = $Connection $Command.CommandText = "ALTER DATABASE tempdb MODIFY FILE (NAME = tempdev, SIZE = 1024MB, filegrowth = 64MB, maxsize=unlimited);" $Command.ExecuteNonQuery() | out-null $Command.CommandText = "ALTER DATABASE tempdb MODIFY FILE (NAME = templog, SIZE = 512MB, filegrowth = 64MB, maxsize=unlimited);" $Command.ExecuteNonQuery() | out-null $Command.CommandText = "ALTER DATABASE tempdb ADD FILE (NAME = tempdev2, FILENAME = '"+$tempDrive+":\MSSQL\$instance\MSSQL10_50.$instance\MSSQL\Data\tempdb2.ndf', SIZE = 1024MB, filegrowth = 64MB, maxsize=unlimited);" $Command.ExecuteNonQuery() | out-null $Command.CommandText = "ALTER DATABASE tempdb ADD FILE (NAME = tempdev3, FILENAME = '"+$tempDrive+":\MSSQL\$instance\MSSQL10_50.$instance\MSSQL\Data\tempdb3.ndf', SIZE = 1024MB, filegrowth = 64MB, maxsize=unlimited);" $Command.ExecuteNonQuery() | out-null $Command.CommandText = "ALTER DATABASE tempdb ADD FILE (NAME = tempdev4, FILENAME = '"+$tempDrive+":\MSSQL\$instance\MSSQL10_50.$instance\MSSQL\Data\tempdb4.ndf', SIZE = 1024MB, filegrowth = 64MB, maxsize=unlimited);" $Command.ExecuteNonQuery() | out-null $Connection.Close() |
Putting all together…
Well, I’ll never paste again all the content here, you can download the script HERE. Just change the file extension from .txt to .ps1.
I know it’s not a rock-solid procedure but it works well for my purposes, feel free to comment or review my script. Just, if you do some improvement on it, please share it and back-link this post!
Cheers
Latest posts by Ludovico (see all)
- New views in Oracle Data Guard 23c - January 3, 2024
- New in Data Guard 21c and 23c: Automatic preparation of the primary - December 22, 2023
- Does FLASHBACK QUERY work across incarnations or after a Data Guard failover? - December 13, 2023
The best and simplest script for automating SQL Server install via Powershell.
Any new ideas for automated installof SQl server? Can we use VHD for on premise instals instaed of uploading to Azure?
Great script, was checking how to change from vbs scripts to powershell and this one is a good start for me. Thanks!!
Yes, with modifications.
For 2012 the command for the installation changes a little:
$installCmd = “.\setup.exe /q /ACTION=Install /IACCEPTSQLSERVERLICENSETERMS /SQLSVCPASSWORD=””$syncSvcAccountPassword”” /AGTSVCPASSWORD=””$syncSvcAccountPassword”” /SAPWD=””$saPassword”” /ConfigurationFile=””$configFile”””
also, the configfile should contain:
[OPTIONS]
instead of
[SQLSERVER2008]
and should NOT contain:
ACTION=””Install””
and
IACCEPTSQLSERVERLICENSETERMS=””True””
They can be passed only through the commandline.
Cannot post it now completely, I have to do some clean up first.
Excellent and clean script compared to SPADE. Does it work with sql 2012?
Due to some reason, service pack install and adding SQL Snapins didn’t work.
I am trouble shooting it.
The web site is great covering all three major databases.
This script has lot of features. But it is not working. Do we need to set the envirionment or any pre requisites before running it in PS 2.0?
Hi Ramki, thank you for your feedback.
Actually I use it without special environments, just start it from the PS console.
Which kind of error do you get?
—
Ludovico
Hi Selva,
please do the following:
1. download the script:
http://www.ludovicocaldara.net/dba/wp-content/uploads/2013/04/SQL2008_install.txt
2. rename it to SQL2008_install.ps1
3. Open the powershell prompt
4. Enter the path to the script and press enter to run it in interactive mode…
Cheers
—
Ludovico
I tried executing the script but some how im not able to… not sure what im missing… can you give me a eg command line to invoke or execute the script in powershell… since im a beginner im not sure how to invoke this script…