├── Common
├── Encode-Html.ps1
├── Test-Credential.ps1
├── Build-SPADENodeAddFolder.ps1
├── Get-Strong-Password.ps1
├── Execute-Powershell.ps1
├── Build-SPADEAddNodeStartScript.ps1
├── Create-Folder.ps1
├── Get-OsVersion.ps1
├── Set-PsExecutionPolicy.ps1
├── Verify-IsAdmin.ps1
├── Get-PortNumber.ps1
├── Execute-SqlScalarQuery.ps1
├── Execute-SqlCommand.ps1
├── Set-PrivateProfileString.ps1
├── Ping-Server.ps1
├── Validate-Strong-Password.ps1
├── Execute-SqlScriptFiles.ps1
├── Execute-Sql.ps1
├── Invoke-WindowsApi.ps1
├── Execute-ScriptFiles.ps1
├── Create-ConfigFile.ps1
├── Write-Log.ps1
└── Copy-InstallFiles.ps1
├── PreScripts
├── 100-OS-Set-TcpOffload.ps1
├── 100-OS-Set-WindowsFirewall.ps1
├── 100-OS-Verify-PageFile.ps1
├── 100-OS-Set-ProcessorPriority.ps1
├── 100-OS-Verify-NetFramework.ps1
├── 200-Service-Check-AncillaryServices.ps1
├── 100-OS-Verify-AdminGroup.ps1
├── 100-OS-Set-Dtc.ps1
└── 100-OS-Verify-Drives.ps1
├── PostScripts
├── 800-Agent-CreateCycleErrorlogJob.sql
├── 800-Agent-CreatePurgeBackupHistoryJob.sql
├── 300-Server-ConfigureNumErrorLogs.sql
├── 300-Server-ResizeDefaultDatabases.sql
├── 800-Agent-Enable-AgentNotifications.ps1
├── 300-Server-Set-MaxServerMemory.ps1
├── 997-Management-RemoveBuiltinAdminsLogin.sql
├── 300-Server-RunSpConfigure.sql
├── 998-Management-Restart-SqlService.ps1
├── 999-Management-Restart-SqlAgentService.ps1
├── 700-Procedure-CreateCycleErrorlogProc.sql
├── 300-Server-Set-LocalSecurityPolicy.ps1
├── _300-Server-ConfigureDatabaseMail.sql
├── 300-Server-ConfigureDatabaseMail.ps1
├── 400-Database-Resize-TempDb.ps1
└── 800-Agent-CreateDatabaseMailCleanupJob.sql
├── Examples
├── PostScripts
│ ├── 800-Agent-CreateHallengrenMaintenanceJobs.sql
│ ├── 700-Procedure-CreateHallengrenCommandExecute.sql
│ ├── 700-Procedure-CreateHallengrenDatabaseBackup.sql
│ ├── 700-Procedure-CreateHallengrenIndexOptimize.sql
│ ├── 700-Procedure-CreateHallengrenDatabaseIntegrityCheck.sql
│ ├── 300-Server-Set-DbaTeam.ps1
│ ├── 345-Server-Set-SqlTcpPort.ps1
│ ├── 900-Management-Add-CmsRegistration.ps1
│ ├── 300-Server-Set-SsisDbInstance.ps1
│ └── 600-Function-CreateHallegrenDtabaseSelect.sql
├── _Template.ps1
├── _Template.sql
└── PreScripts
│ └── 200-Service-Verify-MgmtServerAccess.ps1
├── Templates
├── Configuration_2005.ini
├── Configuration_2014.ini
├── Configuration_2008.ini
├── Configuration_2012.ini
├── Configuration_2008R2.ini
└── Configuration_2016.ini
├── Start-SqlSpade.ps1
├── Tests
└── Run-Install.PreOnly.Tests.ps1
├── README.md
├── appveyor.yml
├── Start.bat
├── Run-Install.config
└── Run-Install.ps1
/Common/Encode-Html.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JasonCarter80/sqlspade/HEAD/Common/Encode-Html.ps1
--------------------------------------------------------------------------------
/Common/Test-Credential.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JasonCarter80/sqlspade/HEAD/Common/Test-Credential.ps1
--------------------------------------------------------------------------------
/PreScripts/100-OS-Set-TcpOffload.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JasonCarter80/sqlspade/HEAD/PreScripts/100-OS-Set-TcpOffload.ps1
--------------------------------------------------------------------------------
/PostScripts/800-Agent-CreateCycleErrorlogJob.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JasonCarter80/sqlspade/HEAD/PostScripts/800-Agent-CreateCycleErrorlogJob.sql
--------------------------------------------------------------------------------
/PostScripts/800-Agent-CreatePurgeBackupHistoryJob.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JasonCarter80/sqlspade/HEAD/PostScripts/800-Agent-CreatePurgeBackupHistoryJob.sql
--------------------------------------------------------------------------------
/Common/Build-SPADENodeAddFolder.ps1:
--------------------------------------------------------------------------------
1 | function Build-SPADENodeAddFolder
2 | {
3 | #Create the folder if it doesn't exist
4 |
5 | #Copy the Run-Install.ps1, Config
6 | }
--------------------------------------------------------------------------------
/Examples/PostScripts/800-Agent-CreateHallengrenMaintenanceJobs.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JasonCarter80/sqlspade/HEAD/Examples/PostScripts/800-Agent-CreateHallengrenMaintenanceJobs.sql
--------------------------------------------------------------------------------
/Examples/PostScripts/700-Procedure-CreateHallengrenCommandExecute.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JasonCarter80/sqlspade/HEAD/Examples/PostScripts/700-Procedure-CreateHallengrenCommandExecute.sql
--------------------------------------------------------------------------------
/Examples/PostScripts/700-Procedure-CreateHallengrenDatabaseBackup.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JasonCarter80/sqlspade/HEAD/Examples/PostScripts/700-Procedure-CreateHallengrenDatabaseBackup.sql
--------------------------------------------------------------------------------
/Examples/PostScripts/700-Procedure-CreateHallengrenIndexOptimize.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JasonCarter80/sqlspade/HEAD/Examples/PostScripts/700-Procedure-CreateHallengrenIndexOptimize.sql
--------------------------------------------------------------------------------
/Examples/PostScripts/700-Procedure-CreateHallengrenDatabaseIntegrityCheck.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JasonCarter80/sqlspade/HEAD/Examples/PostScripts/700-Procedure-CreateHallengrenDatabaseIntegrityCheck.sql
--------------------------------------------------------------------------------
/Common/Get-Strong-Password.ps1:
--------------------------------------------------------------------------------
1 | Function Get-Strong-Password() {
2 | Param(
3 | [int]$length=12
4 | )
5 |
6 | $a = [Reflection.Assembly]::LoadWithPartialName("System.Web")
7 | $([System.Web.Security.Membership]::GeneratePassword($length,$length/4))
8 | }
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Common/Execute-Powershell.ps1:
--------------------------------------------------------------------------------
1 | Function Execute-Powershell
2 | {
3 | param
4 | (
5 | [Parameter(Position=0, Mandatory=$true)] [string] $psScript,
6 | [Parameter(Position=1, Mandatory=$true)] $configParams
7 | )
8 |
9 | return Invoke-Expression -Command "$psScript `$configParams"
10 | }
11 |
--------------------------------------------------------------------------------
/Common/Build-SPADEAddNodeStartScript.ps1:
--------------------------------------------------------------------------------
1 | function Build-SPADEAddNodeStartScript
2 | {
3 |
4 |
5 | #Add dot-sourcing command and declare variables
6 |
7 | #Convert Parameters hashtable to text
8 |
9 | #Convert Overrides hashtable to text
10 |
11 | #Add Run-Install command
12 |
13 | #Save script to folder
14 |
15 | }
--------------------------------------------------------------------------------
/Common/Create-Folder.ps1:
--------------------------------------------------------------------------------
1 | Function Create-Folder
2 | {
3 | param
4 | (
5 | [Parameter(Position=0, Mandatory=$true)] [string] $folderPath
6 | )
7 |
8 | if(test-path $folderPath)
9 | {
10 | Write-Log -level "Info" -message "$folderPath folder already exists"
11 | }
12 | else
13 | {
14 | New-Item $folderPath -itemType Directory | Out-Null
15 | Write-Log -level "Info" -message "$folderPath folder has been created"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Common/Get-OsVersion.ps1:
--------------------------------------------------------------------------------
1 | Function Get-OsVersion
2 | {
3 | $comp = (Get-WmiObject Win32_OperatingSystem | Select Caption)
4 |
5 | switch -wildcard ($comp.Caption)
6 | {
7 | "Microsoft(R) Windows(R) Server 2003*" {$version = "2003"}
8 | "Microsoft Windows Server 2008*" {$version = "2008"}
9 | "Microsoftr Windows Serverr 2008*" {$version = "2008"}
10 | default {$version = "Unknown"}
11 | }
12 | return $version
13 | }
14 |
--------------------------------------------------------------------------------
/Templates/Configuration_2005.ini:
--------------------------------------------------------------------------------
1 | [Options]
2 | PIDKEY="$Key"
3 | INSTALLSQLDIR="C:\Program Files\Microsoft SQL Server"
4 | INSTALLSQLSHAREDDIR="C:\Program Files\Microsoft SQL Server"
5 | INSTALLSQLDATADIR="$SystemDataDir"
6 | ADDLOCAL="$ProductString"
7 | INSTANCENAME="$InstanceName"
8 | SQLBROWSERACCOUNT="$SqlSvcAccount"
9 | SQLACCOUNT="$SqlSvcAccount"
10 | AGTACCOUNT="$AgtSvcAccount"
11 | SQLAUTOSTART=1
12 | AGTAUTOSTART=1
13 | ASAUTOSTART=1
14 | RSAUTOSTART=1
15 | SECURITYMODE="SQL"
16 | SQLCOLLATION="SQL_Latin1_General_CP1_CI_AS"
17 | DISABLENETWORKPROTOCOLS=0
18 | ERRORREPORTING=0
19 | SQMREPORTING=0
20 | ENABLERANU=0
21 |
--------------------------------------------------------------------------------
/PostScripts/300-Server-ConfigureNumErrorLogs.sql:
--------------------------------------------------------------------------------
1 | /* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | /*****************************************************************************************************
4 | * Script Information
5 | *----------------------------------------------------------------------------------------------------
6 | * Description: Set the number of error logs to cycle
7 | *****************************************************************************************************/
8 |
9 | USE [master];
10 |
11 | EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'NumErrorLogs', REG_DWORD, 30;
--------------------------------------------------------------------------------
/Common/Set-PsExecutionPolicy.ps1:
--------------------------------------------------------------------------------
1 | Function Set-PsExecutionPolicy
2 | {
3 | #In both x64 & x86 versions of PowerShell issue a Set-ExecutionPolicy RemoteSigned
4 | $systemRoot = gc env:systemroot
5 | cd $systemRoot
6 | system32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -Command {Set-ExecutionPolicy RemoteSigned -force} #64bit
7 |
8 | if(test-path "syswow64\WindowsPowerShell\v1.0")
9 | {
10 | syswow64\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -Command {Set-ExecutionPolicy RemoteSigned -force} #32bit
11 | }
12 | Write-Log -level "Info" -message "PowerShell Execution Policy set to RemoteSigned"
13 | }
14 |
--------------------------------------------------------------------------------
/Start-SqlSpade.ps1:
--------------------------------------------------------------------------------
1 | #Clear the output window
2 | cls
3 |
4 | #Dot-Source the root function
5 | $Invocation = (Get-Variable MyInvocation).Value
6 | $path = Join-Path (Split-Path $Invocation.MyCommand.Path) Run-Install.ps1
7 | . $path
8 |
9 |
10 | [hashtable] $ht = New-Object hashtable
11 | [hashtable] $overrides = New-Object hashtable
12 |
13 | #Required Parameters
14 | $ht.Add("SqlVersion", 'SQL2008R2') #Valid values - Sql2005, Sql2008, Sql2008R2, Sql2012, Sql2014, Sql2016
15 | $ht.Add("SqlEdition", 'Standard') #Valid values - Standard, Enterprise, Developer (2008R2+)
16 | $ht.Add("SP", 'SP3') #Valid values - Varies by Version
17 | $ht.Add("DataCenter", 'RDP') #Valid values - Values setup in .Config DataCenter section
18 |
19 | ### TODO Show Overrides Here
20 | Run-Install -Parameters $ht -TemplateOverrides $overrides -Full -Confirm:$false
--------------------------------------------------------------------------------
/Common/Verify-IsAdmin.ps1:
--------------------------------------------------------------------------------
1 | Function Verify-IsAdmin
2 | {
3 | $wid=[System.Security.Principal.WindowsIdentity]::GetCurrent()
4 | $prp=new-object System.Security.Principal.WindowsPrincipal($wid)
5 | $adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator
6 | $IsAdmin=$prp.IsInRole($adm)
7 | if ($IsAdmin)
8 | {
9 | #"You are currently running with Administrator priviledges"
10 | #I needed the Out-Null because when -WhatIf or -Confirm are used it produces output to the console
11 | #that interferes with the return value of the function
12 | Write-Log -level "Info" -message ("Script running as admin by {0}" -f $prp.Identity.Name) | Out-Null
13 | return 1
14 | }
15 | else
16 | {
17 | #"Please launch this script again as an administrator"
18 | Write-Log -level "Error" -message "User did not run script as Admin" | Out-Null
19 | return 0
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Tests/Run-Install.PreOnly.Tests.ps1:
--------------------------------------------------------------------------------
1 | Import-Module -Force $PSScriptRoot\..\Run-Install.ps1
2 |
3 | Describe 'Execute PreOnly' {
4 |
5 | Context 'Pre Install Options Only' {
6 |
7 | #Set-StrictMode -Version latest
8 |
9 | It 'Should Not Break' {
10 | $ht.Add("DataCenter", 'Local')
11 | $ht.Add("SqlVersion", 'Sql2012')
12 | $ht.Add("SqlEdition", 'Developer')
13 |
14 | Run-Install -Parameters $ht -TemplateOverrides $overrides -PreOnly
15 | }
16 |
17 | It 'Should Break' {
18 | $ht.Add("SqlVersion", 'Sql2012')
19 | $ht.Add("SqlEdition", 'Developer')
20 | { Run-Install -Parameters $ht -TemplateOverrides $overrides -PreOnly } | Should Throw
21 | }
22 |
23 | BeforeEach {
24 | [hashtable] $ht = New-Object hashtable
25 | [hashtable] $overrides = New-Object hashtable
26 | $ht.Add("FilePath", 'C:\Code\sqlspade\')
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/Common/Get-PortNumber.ps1:
--------------------------------------------------------------------------------
1 | Function Get-PortNumber
2 | {
3 | param(
4 | [hashtable] $configParams
5 | )
6 |
7 | #Load the script parameters from the config file
8 | [array] $nodes = ($Global:ScriptConfigs | ?{$_.Name -eq "Get-PortNumber"}).SelectNodes("Param")
9 | $portNumber = ($nodes | ? {$_.Name -eq "PortNumber"}).Value
10 |
11 | [array] $missing = $nodes | ? {$_.Value -eq ""}
12 | if ($missing.Count -gt 0)
13 | {
14 | Write-Log -level "Attention" -message "Port number not set - please check the Run-Install.config file for missing configuration items"
15 | }
16 |
17 | #Read the PortNumber or set to default value if missing
18 | $port = $configParams["PortNumber"]
19 | if ($port -eq $null -or $port -eq "")
20 | {
21 | $port = $portNumber
22 | }
23 |
24 | $instanceName = $configParams["InstanceName"]
25 | $sqlVersion = $configParams["SqlVersion"]
26 |
27 | #If for some reason we still don't have a valid port number then use the SQL default
28 | if ($port -isnot [int])
29 | {
30 | $port = 1433
31 | }
32 |
33 | return $port
34 | }
35 |
--------------------------------------------------------------------------------
/Common/Execute-SqlScalarQuery.ps1:
--------------------------------------------------------------------------------
1 | Function Execute-SqlScalarQuery
2 | {
3 | param
4 | (
5 | [Parameter(Position=0, Mandatory=$true)] [string] $sqlScript,
6 | [Parameter(Position=1, Mandatory=$true)] [AllowEmptyString()] [string] $sqlInstance,
7 | [Parameter(Position=2, Mandatory=$false)] [string] $serverName = $Global:LogicalComputerName,
8 | [Parameter(Position=3, Mandatory=$false)] [string] $databaseName = "master"
9 | )
10 |
11 | $conn = new-Object System.Data.SqlClient.SqlConnection("Server=$serverName\$sqlInstance;DataBase=$databaseName;Integrated Security=SSPI;")
12 | $sqlCommand = New-Object System.Data.SqlClient.SqlCommand
13 | $sqlCommand.Connection = $conn
14 | $sqlCommand.CommandType = [System.Data.CommandType]'Text'
15 | $sqlCommand.CommandTimeout = 300
16 |
17 | try
18 | {
19 | $conn.Open() | out-null
20 |
21 | $sqlCommand.CommandText = $sqlScript
22 | [int] $retVal = $sqlCommand.ExecuteScalar()
23 |
24 | $strResult = "Command(s) completed successfully."
25 | }
26 | catch [System.Exception]
27 | {
28 | $strResult = $_
29 | }
30 | finally
31 | {
32 | if ($conn.State -ne [System.Data.ConnectionState]'Closed')
33 | {
34 | $conn.Close()
35 | }
36 | }
37 |
38 | return $retVal
39 | }
40 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | SPADE simplifies the process of standing up a new SQL Server instance by applying standard Operating System pre-configurations, Installing SQL Server and then applying post-configurations and creating standard objects.
3 |
4 | SPADE is a tool that is designed to speed up your standard deploymets of SQL Server. You may be saying "But I can already do an unsattended install"...but that's not all that's involved in most server builds. There are Operating System configurations like Microsoft Distrubuted Transaction Coordinator (MSDTC), Local Security Policy and others. I'm sure that you also have standard SQL objects that need to be deployed like Stored Procedures, Agent Jobs, Operators, etc. All of this can be done by SPADE automatically by running 1 simple PowerShell script.
5 |
6 | Every organization is different, so this tool has been built so that it can easily be customized without requiring you to be a master of PowerShell. A simple XML configuration file defines the options for your standard build. For those non-standard, or "one-off" builds, the script has been defined so that you can change things for a single build without having to change the configuration file.
7 |
8 | The current release supports standalone installs of SQL 2005, 2008, 2008R2, 2012, 2014, and 2016 (2017 will be supported soon).
9 |
--------------------------------------------------------------------------------
/Common/Execute-SqlCommand.ps1:
--------------------------------------------------------------------------------
1 | Function Execute-SqlCommand
2 | {
3 | param
4 | (
5 | [Parameter(Position=0, Mandatory=$true)] [string] $sqlScript,
6 | [Parameter(Position=1, Mandatory=$true)] [AllowEmptyString()] [string] $sqlInstance,
7 | [Parameter(Position=2, Mandatory=$false)] [string] $serverName = $Global:LogicalComputerName,
8 | [Parameter(Position=3, Mandatory=$false)] [string] $databaseName = "master"
9 | )
10 |
11 | $conn = new-Object System.Data.SqlClient.SqlConnection("Server=$serverName\$sqlInstance;DataBase=$databaseName;Integrated Security=SSPI;")
12 | $sqlCommand = New-Object System.Data.SqlClient.SqlCommand
13 | $sqlCommand.Connection = $conn
14 | $sqlCommand.CommandType = [System.Data.CommandType]'Text'
15 | $sqlCommand.CommandTimeout = 300
16 |
17 | try
18 | {
19 | $conn.Open() | out-null
20 |
21 | $sqlCommand.CommandText = $sqlScript
22 | $sqlCommand.ExecuteNonQuery() | Out-Null
23 |
24 | $strResult = "Command(s) completed successfully."
25 | }
26 | catch [System.Exception]
27 | {
28 | $strResult = $_
29 | }
30 | finally
31 | {
32 | if ($conn.State -ne [System.Data.ConnectionState]'Closed')
33 | {
34 | $conn.Close()
35 | }
36 | }
37 |
38 | #Write-Log -level "Info" -message "Execute-SqlCommand [DEBUG]: $strResult"
39 | return $strResult
40 | }
41 |
--------------------------------------------------------------------------------
/Common/Set-PrivateProfileString.ps1:
--------------------------------------------------------------------------------
1 | ##############################################################################
2 | ##
3 | ## Set-PrivateProfileString.ps1
4 | ## by Lee Holmes (http://www.leeholmes.com/guide)
5 | ##
6 | ## Set an entry from an INI file.
7 | ##
8 | ## ie:
9 | ##
10 | ## PS >copy C:\winnt\system32\ntfrsrep.ini c:\temp\
11 | ## PS >Set-PrivateProfileString.ps1 C:\temp\ntfrsrep.ini text `
12 | ## >> DEV_CTR_24_009_HELP "New Value"
13 | ## >>
14 | ## PS >Get-PrivateProfileString.ps1 C:\temp\ntfrsrep.ini text DEV_CTR_24_009_HELP
15 | ## New Value
16 | ## PS >Set-PrivateProfileString.ps1 C:\temp\ntfrsrep.ini NEW_SECTION `
17 | ## >> NewItem "Entirely New Value"
18 | ## >>
19 | ## PS >Get-PrivateProfileString.ps1 C:\temp\ntfrsrep.ini NEW_SECTION NewItem
20 | ## Entirely New Value
21 | ##
22 | ##############################################################################
23 | Function Set-PrivateProfileString
24 | {
25 | param(
26 | $file,
27 | $category,
28 | $key,
29 | $value)
30 |
31 | ## Prepare the parameter types and parameter values for the Invoke-WindowsApi script
32 | $parameterTypes = [string], [string], [string], [string]
33 | $parameters = [string] $category, [string] $key, [string] $value, [string] $file
34 |
35 | ## Invoke the API
36 | [void] (Invoke-WindowsApi "kernel32.dll" ([UInt32]) "WritePrivateProfileString" $parameterTypes $parameters)
37 | }
38 |
--------------------------------------------------------------------------------
/Templates/Configuration_2014.ini:
--------------------------------------------------------------------------------
1 | [Options]
2 | PID="$Key"
3 | INSTANCEID="$InstanceId"
4 | ACTION="Install"
5 | FEATURES="$ProductString"
6 | HELP="False"
7 | INDICATEPROGRESS="True"
8 | IACCEPTSQLSERVERLICENSETERMS="True"
9 | QUIET="True"
10 | QUIETSIMPLE="False"
11 | X86="$X86"
12 | PCUSOURCE="$SPSource"
13 | CUSOURCE="$CUSource"
14 | ERRORREPORTING="False"
15 | INSTALLSHAREDDIR="C:\Program Files\Microsoft SQL Server"
16 | INSTALLSHAREDWOWDIR="C:\Program Files (x86)\Microsoft SQL Server"
17 | INSTANCEDIR="C:\Program Files\Microsoft SQL Server"
18 | SQMREPORTING="False"
19 | INSTANCENAME="$InstanceName"
20 | AGTSVCACCOUNT="$AgtSvcAccount"
21 | AGTSVCSTARTUPTYPE="Automatic"
22 | ISSVCSTARTUPTYPE="Manual"
23 | ISSVCACCOUNT="$IsSvcAccount"
24 | ASSVCSTARTUPTYPE="Automatic"
25 | ASCOLLATION="Latin1_General_CI_AS"
26 | ASDATADIR="Data"
27 | ASLOGDIR="Log"
28 | ASBACKUPDIR="Backup"
29 | ASTEMPDIR="Temp"
30 | ASCONFIGDIR="Config"
31 | ASPROVIDERMSOLAP="1"
32 | SQLSVCSTARTUPTYPE="Automatic"
33 | FILESTREAMLEVEL="0"
34 | ENABLERANU="False"
35 | SQLCOLLATION="SQL_Latin1_General_CP1_CI_AS"
36 | SQLSVCACCOUNT="$SqlSvcAccount"
37 | SQLSYSADMINACCOUNTS="$SqlSysAdminAccounts"
38 | SECURITYMODE="SQL"
39 | INSTALLSQLDATADIR="$SystemDataDir"
40 | SQLBACKUPDIR=""
41 | SQLUSERDBDIR=""
42 | SQLUSERDBLOGDIR=""
43 | ADDCURRENTUSERASSQLADMIN="False"
44 | TCPENABLED="1"
45 | NPENABLED="1"
46 | BROWSERSVCSTARTUPTYPE="Automatic"
47 | RSSVCSTARTUPTYPE="Automatic"
48 | RSINSTALLMODE="FilesOnlyMode"
49 | FTSVCACCOUNT="$FTSvcAccount"
50 |
--------------------------------------------------------------------------------
/Templates/Configuration_2008.ini:
--------------------------------------------------------------------------------
1 | [SQLSERVER2008]
2 | PID="$Key"
3 | INSTANCEID="$InstanceId"
4 | ACTION="Install"
5 | FEATURES="$ProductString"
6 | HELP="False"
7 | INDICATEPROGRESS="True"
8 | QUIET="True"
9 | QUIETSIMPLE="False"
10 | X86="$X86"
11 | PCUSOURCE="$SPSource"
12 | CUSOURCE="$CUSource"
13 | ERRORREPORTING="False"
14 | INSTALLSHAREDDIR="C:\Program Files\Microsoft SQL Server"
15 | INSTALLSHAREDWOWDIR="C:\Program Files (x86)\Microsoft SQL Server"
16 | INSTANCEDIR="C:\Program Files\Microsoft SQL Server"
17 | SQMREPORTING="False"
18 | INSTANCENAME="$InstanceName"
19 | AGTSVCACCOUNT="$AgtSvcAccount"
20 | AGTSVCSTARTUPTYPE="Automatic"
21 | ISSVCSTARTUPTYPE="Manual"
22 | ISSVCACCOUNT="$IsSvcAccount"
23 | ASSVCSTARTUPTYPE="Automatic"
24 | ASCOLLATION="Latin1_General_CI_AS"
25 | ASDATADIR="Data"
26 | ASLOGDIR="Log"
27 | ASBACKUPDIR="Backup"
28 | ASTEMPDIR="Temp"
29 | ASCONFIGDIR="Config"
30 | ASPROVIDERMSOLAP="1"
31 | SQLSVCSTARTUPTYPE="Automatic"
32 | FILESTREAMLEVEL="0"
33 | ENABLERANU="False"
34 | SQLCOLLATION="SQL_Latin1_General_CP1_CI_AS"
35 | SQLSVCACCOUNT="$SqlSvcAccount"
36 | SQLSYSADMINACCOUNTS="$SqlSysAdminAccounts"
37 | SECURITYMODE="SQL"
38 | INSTALLSQLDATADIR="$SystemDataDir"
39 | SQLBACKUPDIR=""
40 | SQLUSERDBDIR=""
41 | SQLUSERDBLOGDIR=""
42 | ADDCURRENTUSERASSQLADMIN="False"
43 | TCPENABLED="1"
44 | NPENABLED="1"
45 | BROWSERSVCSTARTUPTYPE="Automatic"
46 | RSSVCSTARTUPTYPE="Automatic"
47 | RSINSTALLMODE="FilesOnlyMode"
48 | FTSVCACCOUNT="$FTSvcAccount"
49 |
--------------------------------------------------------------------------------
/Templates/Configuration_2012.ini:
--------------------------------------------------------------------------------
1 | [Options]
2 | PID="$Key"
3 | INSTANCEID="$InstanceId"
4 | ACTION="Install"
5 | FEATURES="$ProductString"
6 | HELP="False"
7 | INDICATEPROGRESS="True"
8 | IACCEPTSQLSERVERLICENSETERMS="True"
9 | QUIET="True"
10 | QUIETSIMPLE="False"
11 | X86="$X86"
12 | PCUSOURCE="$SPSource"
13 | CUSOURCE="$CUSource"
14 | ERRORREPORTING="False"
15 | INSTALLSHAREDDIR="C:\Program Files\Microsoft SQL Server"
16 | INSTALLSHAREDWOWDIR="C:\Program Files (x86)\Microsoft SQL Server"
17 | INSTANCEDIR="C:\Program Files\Microsoft SQL Server"
18 | SQMREPORTING="False"
19 | INSTANCENAME="$InstanceName"
20 | AGTSVCACCOUNT="$AgtSvcAccount"
21 | AGTSVCSTARTUPTYPE="Automatic"
22 | ISSVCSTARTUPTYPE="Manual"
23 | ISSVCACCOUNT="$IsSvcAccount"
24 | ASSVCSTARTUPTYPE="Automatic"
25 | ASCOLLATION="Latin1_General_CI_AS"
26 | ASDATADIR="Data"
27 | ASLOGDIR="Log"
28 | ASBACKUPDIR="Backup"
29 | ASTEMPDIR="Temp"
30 | ASCONFIGDIR="Config"
31 | ASPROVIDERMSOLAP="1"
32 | SQLSVCSTARTUPTYPE="Automatic"
33 | FILESTREAMLEVEL="0"
34 | ENABLERANU="False"
35 | SQLCOLLATION="SQL_Latin1_General_CP1_CI_AS"
36 | SQLSVCACCOUNT="$SqlSvcAccount"
37 | SQLSYSADMINACCOUNTS="$SqlSysAdminAccounts"
38 | SECURITYMODE="SQL"
39 | INSTALLSQLDATADIR="$SystemDataDir"
40 | SQLBACKUPDIR=""
41 | SQLUSERDBDIR=""
42 | SQLUSERDBLOGDIR=""
43 | ADDCURRENTUSERASSQLADMIN="False"
44 | TCPENABLED="1"
45 | NPENABLED="1"
46 | BROWSERSVCSTARTUPTYPE="Automatic"
47 | RSSVCSTARTUPTYPE="Automatic"
48 | RSINSTALLMODE="FilesOnlyMode"
49 | FTSVCACCOUNT="$FTSvcAccount"
50 |
--------------------------------------------------------------------------------
/Templates/Configuration_2008R2.ini:
--------------------------------------------------------------------------------
1 | [SQLSERVER2008]
2 | PID="$Key"
3 | INSTANCEID="$InstanceId"
4 | ACTION="Install"
5 | FEATURES="$ProductString"
6 | HELP="False"
7 | INDICATEPROGRESS="True"
8 | IACCEPTSQLSERVERLICENSETERMS="True"
9 | QUIET="True"
10 | QUIETSIMPLE="False"
11 | X86="$X86"
12 | PCUSOURCE="$SPSource"
13 | CUSOURCE="$CUSource"
14 | ERRORREPORTING="False"
15 | INSTALLSHAREDDIR="C:\Program Files\Microsoft SQL Server"
16 | INSTALLSHAREDWOWDIR="C:\Program Files (x86)\Microsoft SQL Server"
17 | INSTANCEDIR="C:\Program Files\Microsoft SQL Server"
18 | SQMREPORTING="False"
19 | INSTANCENAME="$InstanceName"
20 | AGTSVCACCOUNT="$AgtSvcAccount"
21 | AGTSVCSTARTUPTYPE="Automatic"
22 | ISSVCSTARTUPTYPE="Manual"
23 | ISSVCACCOUNT="$IsSvcAccount"
24 | ASSVCSTARTUPTYPE="Automatic"
25 | ASCOLLATION="Latin1_General_CI_AS"
26 | ASDATADIR="Data"
27 | ASLOGDIR="Log"
28 | ASBACKUPDIR="Backup"
29 | ASTEMPDIR="Temp"
30 | ASCONFIGDIR="Config"
31 | ASPROVIDERMSOLAP="1"
32 | SQLSVCSTARTUPTYPE="Automatic"
33 | FILESTREAMLEVEL="0"
34 | ENABLERANU="False"
35 | SQLCOLLATION="SQL_Latin1_General_CP1_CI_AS"
36 | SQLSVCACCOUNT="$SqlSvcAccount"
37 | SQLSYSADMINACCOUNTS="$SqlSysAdminAccounts"
38 | SECURITYMODE="SQL"
39 | INSTALLSQLDATADIR="$SystemDataDir"
40 | SQLBACKUPDIR=""
41 | SQLUSERDBDIR=""
42 | SQLUSERDBLOGDIR=""
43 | ADDCURRENTUSERASSQLADMIN="False"
44 | TCPENABLED="1"
45 | NPENABLED="1"
46 | BROWSERSVCSTARTUPTYPE="Automatic"
47 | RSSVCSTARTUPTYPE="Automatic"
48 | RSINSTALLMODE="FilesOnlyMode"
49 | FTSVCACCOUNT="$FTSvcAccount"
50 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | install:
2 | - cinst pester
3 |
4 | build: false
5 |
6 | test_script:
7 | - ps: $spadeBase = "C:\Code\sqlSpade\"
8 | - ps: $sqlBase = "C:\Code\MSSQL\"
9 | - ps: Copy-Item "." $spadeBase -Force -Recurse
10 | - ps: $versions = @(
11 | "SQL2005\X86","SQL2005\X64","SQL2005\SP","SQL2005\SP\SP1","SQL2005\SP\SP2","SQL2005\SP\SP3","SQL2005\SP\SP4","SQL2008\Enterprise",
12 | "SQL2008\Standard","SQL2008\Developer","SQL2008\SP","SQL2008\SP\SP1","SQL2008\SP\SP2","SQL2008\SP\SP3","SQL2008\SP\SP4","SQL2008R2\Enterprise",
13 | "SQL2008R2\Standard","SQL2008R2\Developer","SQL2008R2\SP","SQL2008R2\SP\SP1","SQL2008R2\SP\SP2","SQL2008R2\SP\SP3",
14 | "SQL2012\Enterprise","SQL2012\Standard","SQL2012\Developer","SQL2012\SP","SQL2012\SP\SP1","SQL2012\SP\SP2","SQL2012\SP\SP3",
15 | "SQL2014\Enterprise","SQL2014\Standard","SQL2014\Developer","SQL2014\SP","SQL2014\SP\SP1","SQL2014\SP\SP2",
16 | "SQL2016\Enterprise","SQL2016\Standard","SQL2016\Developer","SQL2016\SP"
17 | )
18 | - ps: $versions | % { if (!(Test-Path -Path (Join-Path $sqlBase $_))) { $a = New-Item -Type Directory -Path (Join-Path $sqlBase $_)}}
19 | - ps: $res = Invoke-Pester -Path (Join-Path $spadeBase "Tests") -OutputFormat NUnitXml -OutputFile (Join-Path $spadeBase TestsResults.xml) -PassThru
20 | - ps: Get-ChildItem (Join-Path $spadeBase "Logs\*.*") | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name }
21 | - ps: (New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path (Join-Path $spadeBase TestsResults.xml)))
22 | - ps: if ($res.FailedCount -gt 0) { throw "$($res.FailedCount) tests failed."}
23 |
24 |
--------------------------------------------------------------------------------
/Common/Ping-Server.ps1:
--------------------------------------------------------------------------------
1 | Function Ping-Server
2 | {
3 | param
4 | (
5 | [string] $serverName=$(throw "Server Name is required")
6 | )
7 | #This uses the ping command line utility and parses the results
8 | # [array] $pingResults = $(ping $serverName)
9 | # [string] $formattedResults = "Ping results for $serverName \n "
10 | # foreach($line in $pingResults)
11 | # {
12 | # $formattedResults += ($line + " \n ")
13 | # }
14 | #
15 | # return $formattedResults
16 |
17 | #This uses WMI and requires no parsing
18 | $statusCode = (get-wmiobject win32_pingstatus -Filter "address='$serverName'").StatusCode
19 |
20 | $result = ""
21 | switch ($statusCode)
22 | {
23 | 0 {$result = "Success"}
24 | 11001 {$result = "Buffer Too Small"}
25 | 11002 {$result = "Destination Net Unreachable"}
26 | 11003 {$result = "Destination Host Unreachable"}
27 | 11004 {$result = "Destination Protocol Unreachable"}
28 | 11005 {$result = "Destination Port Unreachable"}
29 | 11006 {$result = "No Resources"}
30 | 11007 {$result = "Bad Option"}
31 | 11008 {$result = "Hardware Error"}
32 | 11009 {$result = "Packet Too Big"}
33 | 11010 {$result = "Request Timed Out"}
34 | 11011 {$result = "Bad Request"}
35 | 11012 {$result = "Bad Route"}
36 | 11013 {$result = "TimeToLive Expired Transit"}
37 | 11014 {$result = "TimeToLive Expired Reassembly"}
38 | 11015 {$result = "Parameter Problem"}
39 | 11016 {$result = "Source Quench"}
40 | 11017 {$result = "Option Too Big"}
41 | 11018 {$result = "Bad Destination"}
42 | 11032 {$result = "Negotiating IPSEC"}
43 | 11050 {$result = "General Failure"}
44 | default {$result = "Unknown Failure"}
45 | }
46 |
47 | return $result
48 | }
49 |
--------------------------------------------------------------------------------
/Templates/Configuration_2016.ini:
--------------------------------------------------------------------------------
1 | [Options]
2 | PID="$Key"
3 | INSTANCEID="$InstanceId"
4 | ACTION="Install"
5 | FEATURES="$ProductString"
6 | HELP="False"
7 | INDICATEPROGRESS="True"
8 | IACCEPTSQLSERVERLICENSETERMS="True"
9 | QUIET="True"
10 | QUIETSIMPLE="False"
11 | X86="$X86"
12 | PCUSOURCE="$SPSource"
13 | CUSOURCE="$CUSource"
14 | ERRORREPORTING="False"
15 | INSTALLSHAREDDIR="C:\Program Files\Microsoft SQL Server"
16 | INSTALLSHAREDWOWDIR="C:\Program Files (x86)\Microsoft SQL Server"
17 | INSTANCEDIR="C:\Program Files\Microsoft SQL Server"
18 | SQMREPORTING="False"
19 | INSTANCENAME="$InstanceName"
20 | AGTSVCACCOUNT="$AgtSvcAccount"
21 | AGTSVCSTARTUPTYPE="Automatic"
22 | ISSVCSTARTUPTYPE="Manual"
23 | ISSVCACCOUNT="$IsSvcAccount"
24 | ASSVCSTARTUPTYPE="Automatic"
25 | ASCOLLATION="Latin1_General_CI_AS"
26 | ASDATADIR="Data"
27 | ASLOGDIR="Log"
28 | ASSERVERMODE="TABULAR"
29 | ASBACKUPDIR="Backup"
30 | ASTEMPDIR="Temp"
31 | ASCONFIGDIR="Config"
32 | ASPROVIDERMSOLAP="1"
33 | SQLSVCSTARTUPTYPE="Automatic"
34 | FILESTREAMLEVEL="0"
35 | ENABLERANU="False"
36 | SQLCOLLATION="SQL_Latin1_General_CP1_CI_AS"
37 | SQLSVCACCOUNT="$SqlSvcAccount"
38 | SQLSYSADMINACCOUNTS="$SqlSysAdminAccounts"
39 | SECURITYMODE="SQL"
40 | SQLTEMPDBDIR="C:\TempDB\"
41 | SQLTEMPDBLOGDIR="C:\TempDB\"
42 | SQLTEMPDBFILESIZE="1024"
43 | SQLTEMPDBFILEGROWTH="1024"
44 | SQLTEMPDBLOGFILESIZE="1024"
45 | SQLTEMPDBLOGFILEGROWTH="1024"
46 | INSTALLSQLDATADIR="$SystemDataDir"
47 | SQLSVCINSTANTFILEINIT="True"
48 | SQLBACKUPDIR=""
49 | SQLUSERDBDIR=""
50 | SQLUSERDBLOGDIR=""
51 | ADDCURRENTUSERASSQLADMIN="False"
52 | TCPENABLED="1"
53 | NPENABLED="1"
54 | BROWSERSVCSTARTUPTYPE="Automatic"
55 | RSSVCSTARTUPTYPE="Automatic"
56 | RSINSTALLMODE="FilesOnlyMode"
57 | FTSVCACCOUNT="$FTSvcAccount"
58 | PBENGSVCSTARTUPTYPE="Automatic"
59 | PBPORTRANGE="16450-16460"
60 | PBSCALEOUT="False"
61 |
62 |
63 |
--------------------------------------------------------------------------------
/Common/Validate-Strong-Password.ps1:
--------------------------------------------------------------------------------
1 |
2 | Function Validate-Strong-Password {
3 |
4 | param(
5 | [string]$Password = $(throw "Please specify password"),
6 | [int]$minLength=8,
7 | [int]$numUpper = 1,
8 | [int]$numLower = 1,
9 | [int]$numNumbers = 1,
10 | [int]$numSpecial = 1,
11 | [int]$minGroups = 3
12 | )
13 |
14 |
15 | $upper = [regex]"[A-Z]"
16 | $lower = [regex]"[a-z]"
17 | $number = [regex]"[0-9]"
18 | $special = [regex]"[^a-zA-Z0-9]"
19 | $groups = 0
20 | # Check the length.
21 |
22 | if ($Password.length -lt $minLength)
23 | {
24 | Write-Log -Level Debug "Password does not meet Minimum Length Requirement of $minLength"
25 | return $false;
26 | }
27 |
28 |
29 | # Check for minimum number of occurrences.
30 | if ($upper.Matches($Password).Count -lt $numUpper )
31 | {
32 | Write-Log -Level Debug "Password does not meet Upper Case Letter Requirement of $numUpper"
33 | return $false;
34 | }
35 | else
36 | {
37 | $group += 1
38 | }
39 |
40 | if ($lower.Matches($Password).Count -lt $numLower )
41 | {
42 | Write-Log -Level Debug "Password does not meet Lower Case Letter Requirement of $numLower"
43 | return $false;
44 | }
45 | else
46 | {
47 | $group += 1
48 | }
49 |
50 | if ($number.Matches($Password).Count -lt $numNumbers )
51 | {
52 | Write-Log -Level Debug "Password does not meet Numbers Requirement of $numNumbers"
53 | return $false;
54 | }
55 | else
56 | {
57 | $group += 1
58 | }
59 |
60 | if ($special.Matches($Password).Count -lt $numSpecial )
61 | {
62 | Write-Log -Level Debug "Password does not meet Special Character Requirement of $numSpecial"
63 | return $false;
64 | }
65 | else
66 | {
67 | $group += 1
68 | }
69 |
70 | if ($group -lt $minGroups)
71 | {
72 | Write-Log -Level Debug "Password does not meet Matches Per Group of $minGroups"
73 | return $false;
74 | }
75 |
76 |
77 | return $true
78 | }
79 |
--------------------------------------------------------------------------------
/Examples/_Template.ps1:
--------------------------------------------------------------------------------
1 | #/* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | ###############################################################################################################
4 | # PowerShell Script Template
5 | ###############################################################################################################
6 | # For use with the Auto-Install process
7 | #
8 | # When called, the script will recieve a single hashtable object passed as a parameter.
9 | # This object contains the following items by default:
10 | # SqlVersion - version being installed
11 | # SqlEdition - edition being installed
12 | # ServiceAccount - service account being used
13 | # ServicePassword - password for service account
14 | # SysAdminPassword - SA password
15 | # FilePath - working folder for auto-install
16 | # DataCenter - data center the server is located in
17 | # DbaTeam - responsible DBA team
18 | # InstanceName - SQL instance name
19 | # ProductStringName - product features being installed
20 | # Environment - environment for server (dev, qa, bcp, prod)
21 | #
22 | # Additional items can be added by using the Add method on the $ht object in the Start-SqlSpade.ps1 script
23 | #
24 | # You can access any of these items using the following syntax: $configParams["SqlVersion"]
25 | #
26 | # This script should be placed in the appropriate scripts folder and will be automatically called during the
27 | # auto-install process.
28 | #
29 | # The script should be saved using the following naming convention:
30 | #
31 | # Pre Install Script (Save to PreScripts Folder) -
32 | # -------------------------------------------------
33 | # Pre-100-OS-[ScriptName].ps1
34 | # Pre-200-Service-[ScriptName].ps1
35 | #
36 | # Post Install Script (Save to SQLScripts Folder) -
37 | # -------------------------------------------------
38 | # 100-OS-[ScriptName].ps1
39 | # 200-Service-[ScriptName].ps1
40 | # 300-Server-[ScriptName].ps1
41 | # 400-Database-[ScriptName].ps1
42 | # 500-Table-[ScriptName].ps1
43 | # 600-View-[ScriptName].ps1
44 | # 700-Procedure-[ScriptName].ps1
45 | # 800-Agent-[ScriptName].ps1
46 | # 900-Management-ScriptName.ps1
47 | ###############################################################################################################
48 |
49 | $configParams = $args[0]
--------------------------------------------------------------------------------
/PreScripts/100-OS-Set-WindowsFirewall.ps1:
--------------------------------------------------------------------------------
1 | #/* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | ###############################################################################################################
4 | # PowerShell Script Template
5 | ###############################################################################################################
6 | # For use with the Auto-Install process
7 | #
8 | # When called, the script will recieve a single hashtable object passed as a
9 | # parameter. This object contains the following properties:
10 | # $params["SqlVersion"] - Version of SQL being installed (SQL2005, SQL2008, SQL2008R2)
11 | # $params["SqlEdition"] - Edition of SQL being installed (Standard, Enterprise)
12 | # $params["ProcessorArch"] - CPU Architecture (x86, X64)
13 | # $params["InstanceName"] - The name that the instance will be installed with (sqldev1)
14 | # $params["ServiceAccount"] - The name of the account to run the services under (domain\user)
15 | # $params["FilePath"] - path to save the configuration ini file
16 | #
17 | # To add additional parameters - add them to the hashtable passed to the Run-Install function
18 | #
19 | # This script should be placed in the appropriate scripts folder and will be automatically called during the
20 | # auto-install process.
21 | #
22 | # The script should be saved using the following naming convention:
23 | #
24 | # Pre Install Script (Save to PreScripts Folder) -
25 | # -------------------------------------------------
26 | # Pre-100-OS-[ScriptName].ps1
27 | # Pre-200-Service-[ScriptName].ps1
28 | #
29 | # Post Install Script (Save to SQLScripts Folder) -
30 | # -------------------------------------------------
31 | # 100-OS-[ScriptName].ps1
32 | # 200-Service-[ScriptName].ps1
33 | # 300-Server-[ScriptName].ps1
34 | # 400-Database-[ScriptName].ps1
35 | # 500-Table-[ScriptName].ps1
36 | # 600-View-[ScriptName].ps1
37 | # 700-Procedure-[ScriptName].ps1
38 | # 800-Agent-[ScriptName].ps1
39 | ###############################################################################################################
40 |
41 | $configParams = $args[0]
42 |
43 | $cmdResult = netsh advfirewall "set" "domainprofile" "firewallpolicy" "allowinbound,allowoutbound"
44 |
45 | Write-Log -level "Info" -message "Windows Firewall Domain Profile complete - $cmdResult"
46 |
--------------------------------------------------------------------------------
/PreScripts/100-OS-Verify-PageFile.ps1:
--------------------------------------------------------------------------------
1 | #/* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | ###############################################################################################################
4 | # PowerShell Script Template
5 | ###############################################################################################################
6 | # For use with the Auto-Install process
7 | #
8 | # When called, the script will recieve a single hashtable object passed as a
9 | # parameter. This object contains the following properties:
10 | # $params["SqlVersion"] - Version of SQL being installed (SQL2005, SQL2008, SQL2008R2)
11 | # $params["SqlEdition"] - Edition of SQL being installed (Standard, Enterprise)
12 | # $params["ProcessorArch"] - CPU Architecture (x86, X64)
13 | # $params["InstanceName"] - The name that the instance will be installed with (sqldev1)
14 | # $params["ServiceAccount"] - The name of the account to run the services under (domain\user)
15 | # $params["FilePath"] - path to save the configuration ini file
16 | #
17 | # To add additional parameters - add them to the hashtable passed to the Run-Install function
18 | #
19 | # This script should be placed in the appropriate scripts folder and will be automatically called during the
20 | # auto-install process.
21 | #
22 | # The script should be saved using the following naming convention:
23 | #
24 | # Pre Install Script (Save to PreScripts Folder) -
25 | # -------------------------------------------------
26 | # Pre-100-OS-[ScriptName].ps1
27 | # Pre-200-Service-[ScriptName].ps1
28 | #
29 | # Post Install Script (Save to SQLScripts Folder) -
30 | # -------------------------------------------------
31 | # 100-OS-[ScriptName].ps1
32 | # 200-Service-[ScriptName].ps1
33 | # 300-Server-[ScriptName].ps1
34 | # 400-Database-[ScriptName].ps1
35 | # 500-Table-[ScriptName].ps1
36 | # 600-View-[ScriptName].ps1
37 | # 700-Procedure-[ScriptName].ps1
38 | # 800-Agent-[ScriptName].ps1
39 | ###############################################################################################################
40 |
41 | $configParams = $args[0]
42 |
43 | #Verify that page file size on the C: drive is 2GB
44 | $winOS = Get-WMIObject Win32_OperatingSystem
45 | $swapFile = $winOS.SizeStoredInPagingFiles
46 | $pageFile = Get-WmiObject Win32_PageFileUsage
47 | [int]$swapFile = $swapFile/1024
48 | Write-Log -level "Info" -message ("The page file is {0} MB located at {1}" -f $swapFile,$pageFile.Name)
49 |
--------------------------------------------------------------------------------
/PreScripts/100-OS-Set-ProcessorPriority.ps1:
--------------------------------------------------------------------------------
1 | #/* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | ###############################################################################################################
4 | # PowerShell Script Template
5 | ###############################################################################################################
6 | # For use with the Auto-Install process
7 | #
8 | # When called, the script will recieve a single hashtable object passed as a
9 | # parameter. This object contains the following properties:
10 | # $params["SqlVersion"] - Version of SQL being installed (SQL2005, SQL2008, SQL2008R2)
11 | # $params["SqlEdition"] - Edition of SQL being installed (Standard, Enterprise)
12 | # $params["ProcessorArch"] - CPU Architecture (x86, X64)
13 | # $params["InstanceName"] - The name that the instance will be installed with (sqldev1)
14 | # $params["ServiceAccount"] - The name of the account to run the services under (domain\user)
15 | # $params["FilePath"] - path to save the configuration ini file
16 | #
17 | # To add additional parameters - add them to the hashtable passed to the Run-Install function
18 | #
19 | # This script should be placed in the appropriate scripts folder and will be automatically called during the
20 | # auto-install process.
21 | #
22 | # The script should be saved using the following naming convention:
23 | #
24 | # Pre Install Script (Save to PreScripts Folder) -
25 | # -------------------------------------------------
26 | # Pre-100-OS-[ScriptName].ps1
27 | # Pre-200-Service-[ScriptName].ps1
28 | #
29 | # Post Install Script (Save to SQLScripts Folder) -
30 | # -------------------------------------------------
31 | # 100-OS-[ScriptName].ps1
32 | # 200-Service-[ScriptName].ps1
33 | # 300-Server-[ScriptName].ps1
34 | # 400-Database-[ScriptName].ps1
35 | # 500-Table-[ScriptName].ps1
36 | # 600-View-[ScriptName].ps1
37 | # 700-Procedure-[ScriptName].ps1
38 | # 800-Agent-[ScriptName].ps1
39 | ###############################################################################################################
40 |
41 | $configParams = $args[0]
42 |
43 | #Verify MS Best Practices for SQL have been implemented
44 | #Only piece that applies to Windows Server 2008 is the Processor Scheduling
45 | Set-ItemProperty -path "HKLM:\SYSTEM\CurrentControlSet\Control\PriorityControl" -name "Win32PrioritySeparation" -value 0x26 #Programs
46 | Write-Log -level "Info" -message "Processor priority set to Programs"
47 |
--------------------------------------------------------------------------------
/PostScripts/300-Server-ResizeDefaultDatabases.sql:
--------------------------------------------------------------------------------
1 | /* 2005,2008,2008R2,2012,2014,2016 */
2 | /*****************************************************************************************************
3 | * Script Information
4 | *----------------------------------------------------------------------------------------------------
5 | * Author: Jason Carter
6 | * Date: 11/07/2016
7 | * Description: Resize Default Databases
8 | * History: 08/15/2016 - Adapted to Auto-Install script
9 | *
10 | *****************************************************************************************************/
11 |
12 | USE [master];
13 |
14 |
15 | ---- Adjust Default Database Options
16 | IF NOT EXISTS(select * from sys.master_files where name='master' and size>=8192)
17 | BEGIN
18 | ALTER DATABASE [master] MODIFY FILE (NAME = master, SIZE = 64MB, FILEGROWTH = 64MB)
19 | PRINT 'Master Database Sizes Set (Initial/Growth): 64MB / 64MB'
20 | END
21 |
22 | IF NOT EXISTS(select * from sys.master_files where name='mastlog' and size>=2048)
23 | BEGIN
24 | ALTER DATABASE [master] MODIFY FILE (NAME = mastlog, SIZE = 16MB, FILEGROWTH = 16MB)
25 | PRINT 'Master Database Log Sizes Set (Initial/Growth): 16MB / 16MB'
26 | END
27 |
28 | IF NOT EXISTS(Select * from sys.databases where name = N'model' and recovery_model=3)
29 | BEGIN
30 | ALTER DATABASE [Model] SET RECOVERY SIMPLE
31 | PRINT 'Model Database Set to SIMPLE RECOVERY MODE'
32 | END
33 |
34 | IF NOT EXISTS(select * from sys.master_files where name='modeldev' and size>=16384)
35 | BEGIN
36 | ALTER DATABASE [Model] MODIFY FILE (NAME = 'modeldev', SIZE = 128MB, FILEGROWTH = 64MB)
37 | PRINT 'Model Database Sizes Set (Initial/Growth): 128MB / 64MB'
38 | END
39 |
40 | IF NOT EXISTS(select * from sys.master_files where name='modellog' and size>=4096)
41 | BEGIN
42 | ALTER DATABASE [Model] MODIFY FILE (NAME = 'modellog', SIZE = 32MB, FILEGROWTH = 32MB)
43 | PRINT '[Model] Database Log Sizes Set (Initial/Growth): 32MB / 32MB'
44 | END
45 |
46 | IF NOT EXISTS(select * from sys.master_files where name='MSDBData' and size>=32768)
47 | BEGIN
48 | ALTER DATABASE [MSDB] MODIFY FILE (NAME = 'MSDBData', SIZE = 256MB, FILEGROWTH = 64MB)
49 | PRINT '[MSDB] Database Sizes Set (Initial/Growth): 256MB / 64MB'
50 | END
51 |
52 | IF NOT EXISTS(select * from sys.master_files where name='MSDBLog' and size>=4096)
53 | BEGIN
54 | ALTER DATABASE [MSDB] MODIFY FILE (NAME = 'MSDBLog', SIZE = 32MB, FILEGROWTH = 32MB)
55 | PRINT '[MSDB] Database Log Sizes Set (Initial/Growth): 32MB / 32MB'
56 | END
--------------------------------------------------------------------------------
/Examples/PostScripts/300-Server-Set-DbaTeam.ps1:
--------------------------------------------------------------------------------
1 | #/* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | ###############################################################################################################
4 | # PowerShell Script Template
5 | ###############################################################################################################
6 | # For use with the Auto-Install process
7 | #
8 | # When called, the script will recieve a single hashtable object passed as a
9 | # parameter. This object contains the following properties:
10 | # $params["SqlVersion"] - Version of SQL being installed (SQL2005, SQL2008, SQL2008R2)
11 | # $params["SqlEdition"] - Edition of SQL being installed (Standard, Enterprise)
12 | # $params["ProcessorArch"] - CPU Architecture (x86, X64)
13 | # $params["InstanceName"] - The name that the instance will be installed with (sqldev1)
14 | # $params["ServiceAccount"] - The name of the account to run the services under (domain\user)
15 | # $params["FilePath"] - path to save the configuration ini file
16 | #
17 | # To add additional parameters - add them to the hashtable passed to the Run-Install function
18 | #
19 | # This script should be placed in the appropriate scripts folder and will be automatically called during the
20 | # auto-install process.
21 | #
22 | # The script should be saved using the following naming convention:
23 | #
24 | # Pre Install Script (Save to PreScripts Folder) -
25 | # -------------------------------------------------
26 | # Pre-100-OS-[ScriptName].ps1
27 | # Pre-200-Service-[ScriptName].ps1
28 | #
29 | # Post Install Script (Save to SQLScripts Folder) -
30 | # -------------------------------------------------
31 | # 100-OS-[ScriptName].ps1
32 | # 200-Service-[ScriptName].ps1
33 | # 300-Server-[ScriptName].ps1
34 | # 400-Database-[ScriptName].ps1
35 | # 500-Table-[ScriptName].ps1
36 | # 600-View-[ScriptName].ps1
37 | # 700-Procedure-[ScriptName].ps1
38 | # 800-Agent-[ScriptName].ps1
39 | # 900-Management-[ScriptName].ps1
40 | ###############################################################################################################
41 |
42 | $configParams = $args[0]
43 | $dbaTeam = $configParams["DbaTeam"]
44 | $instance = $configParams["InstanceName"]
45 |
46 | $command = "
47 | use master;
48 | EXEC sp_addextendedproperty @name = N'DBA', @value = '$dbaTeam';
49 | use model;
50 | EXEC sp_addextendedproperty @name = N'DBA', @value = '$dbaTeam';"
51 |
52 | Execute-SqlCommand -sqlScript $command -sqlInstance $instance
53 |
54 | Write-Log -level "Info" -message "The DBA extended property has been added to Master and Model with the value of $dbaTeam"
55 |
--------------------------------------------------------------------------------
/PreScripts/100-OS-Verify-NetFramework.ps1:
--------------------------------------------------------------------------------
1 | #/* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | ###############################################################################################################
4 | # PowerShell Script Template
5 | ###############################################################################################################
6 | # For use with the Auto-Install process
7 | #
8 | # When called, the script will recieve a single hashtable object passed as a
9 | # parameter. This object contains the following properties:
10 | # $params["SqlVersion"] - Version of SQL being installed (SQL2005, SQL2008, SQL2008R2)
11 | # $params["SqlEdition"] - Edition of SQL being installed (Standard, Enterprise)
12 | # $params["ProcessorArch"] - CPU Architecture (x86, X64)
13 | # $params["InstanceName"] - The name that the instance will be installed with (sqldev1)
14 | # $params["ServiceAccount"] - The name of the account to run the services under (domain\user)
15 | # $params["FilePath"] - path to save the configuration ini file
16 | #
17 | # To add additional parameters - add them to the hashtable passed to the Run-Install function
18 | #
19 | # This script should be placed in the appropriate scripts folder and will be automatically called during the
20 | # auto-install process.
21 | #
22 | # The script should be saved using the following naming convention:
23 | #
24 | # Pre Install Script (Save to PreScripts Folder) -
25 | # -------------------------------------------------
26 | # Pre-100-OS-[ScriptName].ps1
27 | # Pre-200-Service-[ScriptName].ps1
28 | #
29 | # Post Install Script (Save to SQLScripts Folder) -
30 | # -------------------------------------------------
31 | # 100-OS-[ScriptName].ps1
32 | # 200-Service-[ScriptName].ps1
33 | # 300-Server-[ScriptName].ps1
34 | # 400-Database-[ScriptName].ps1
35 | # 500-Table-[ScriptName].ps1
36 | # 600-View-[ScriptName].ps1
37 | # 700-Procedure-[ScriptName].ps1
38 | # 800-Agent-[ScriptName].ps1
39 | ###############################################################################################################
40 |
41 | $configParams = $args[0]
42 |
43 | #Verify .NetFramework 3.5 SP1 is installed
44 | $framework = Get-ItemProperty -path "HKLM:\Software\Microsoft\NET Framework Setup\ndp\v3.5" -name "SP"
45 | if($framework.SP -ge 1)
46 | {
47 | #Correct version installed
48 | Write-Log -level "Info" -message ("The .net framework 3.5 is at SP 1 or greater - SP{0}" -f $framework.SP)
49 | }
50 | else
51 | {
52 | #Not the correct version
53 | Write-Log -level "Error" -message ("The .net framework 3.5 needs to be SP 1 or greater - SP{0}" -f $framework.SP)
54 | }
55 |
--------------------------------------------------------------------------------
/Common/Execute-SqlScriptFiles.ps1:
--------------------------------------------------------------------------------
1 | Function Execute-SqlScriptFiles
2 | {
3 | param
4 | (
5 | [Parameter(Position=0, Mandatory=$true)] [string] $sqlVersion,
6 | [Parameter(Position=1, Mandatory=$true)] [string] $sqlInstance
7 | )
8 |
9 | #$tempPath = [environment]::GetEnvironmentVariable("temp","machine")
10 | #$tempPath
11 | #$Script:LogFile = join-path -path $tempPath -childPath "SqlInstallerLog_ScriptTest.html"
12 |
13 | #Load a list of all files from the scripts folder (\\ray\dba_public$\cur_installs\SqlScripts)
14 | [array] $files = get-childitem -path '\\walrus1xb\f$\cur_installs\sqlscripts' -filter '*.sql'
15 |
16 | #Sort the list on file name (file name should start with script level - 100 OS, 200 Service, 300 Server, 400 Database, 500 Table, 600 View, 700 Procedure, 800 Agent)
17 | $files = $files | Sort-Object
18 |
19 | Write-Log -level "Section" -message "Applying Standard SQL Scripts"
20 |
21 | #Loop through the list
22 | foreach ($file in $files)
23 | {
24 | #Read the first line of each file (/* 2005,2008,2008R2 */)
25 | [string] $strSupported = Get-Content -Path $file.FullName -TotalCount 1
26 |
27 | #Clean off the /* */ from the first line and split to a string array
28 | #Original code - .Net method using the replace method of the string object
29 | #[array] $arySupported = $strSupported.Replace('/*', '').Replace('*/', '').Trim().Split(',')
30 |
31 | #Code showing the PowerShell + RegEx method of performing the same task
32 | $arySupported = $strSupported -replace '/\*|\*/' -replace '^\s+|\s+$' -split ','
33 |
34 | #If the current version is contained in the array then execute the script using the Execute-Sql function
35 | if ($arySupported -contains $($sqlVersion -replace "sql"))
36 | {
37 | #Write the script name and results (query results or skipped) to the log
38 | Write-Log -level "Info" -message "Executing SQL Script - $file"
39 |
40 | #Check to see if we are connecting to a default instance
41 | if ([string]::IsNullOrEmpty($sqlInstance))
42 | {
43 | $strResult = Execute-SQL -sqlScript $file.FullName
44 | }
45 | else
46 | {
47 | $strResult = Execute-SQL -sqlScript $file.FullName -sqlInstance $sqlInstance
48 | }
49 |
50 | if ($strResult -eq "Command(s) completed successfully.")
51 | {
52 | Write-Log -level "Info" -message "$file - $strResult"
53 | }
54 | else
55 | {
56 | Write-Log -level "Warning" -message "$file - Failed: $strResult"
57 | if ($sqlConn.State -ne [System.Data.ConnectionState]'Closed')
58 | {
59 | $sqlConn.Close()
60 | Write-Log -level "Info" -message "Closing Connection"
61 | }
62 | }
63 | }
64 | else
65 | {
66 | Write-Log -level "Feature" -message "Skipping SQL Script - $file"
67 | }
68 | #Next
69 | }
70 | Write-Log -level "Info" -message "Standard SQL Scripts Complete"
71 | }
72 |
--------------------------------------------------------------------------------
/PostScripts/800-Agent-Enable-AgentNotifications.ps1:
--------------------------------------------------------------------------------
1 | #/* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | ###############################################################################################################
4 | # PowerShell Script Template
5 | ###############################################################################################################
6 | # For use with the Auto-Install process
7 | #
8 | # When called, the script will recieve a single hashtable object passed as a
9 | # parameter. This object contains the following properties:
10 | # $params["SqlVersion"] - Version of SQL being installed (SQL2005, SQL2008, SQL2008R2)
11 | # $params["SqlEdition"] - Edition of SQL being installed (Standard, Enterprise)
12 | # $params["ProcessorArch"] - CPU Architecture (x86, X64)
13 | # $params["InstanceName"] - The name that the instance will be installed with (sqldev1)
14 | # $params["ServiceAccount"] - The name of the account to run the services under (domain\user)
15 | # $params["FilePath"] - path to save the configuration ini file
16 | #
17 | # To add additional parameters - add them to the hashtable passed to the Run-Install function
18 | #
19 | # This script should be placed in the appropriate scripts folder and will be automatically called during the
20 | # auto-install process.
21 | #
22 | # The script should be saved using the following naming convention:
23 | #
24 | # Pre Install Script (Save to PreScripts Folder) -
25 | # -------------------------------------------------
26 | # Pre-100-OS-[ScriptName].ps1
27 | # Pre-200-Service-[ScriptName].ps1
28 | #
29 | # Post Install Script (Save to SQLScripts Folder) -
30 | # -------------------------------------------------
31 | # 100-OS-[ScriptName].ps1
32 | # 200-Service-[ScriptName].ps1
33 | # 300-Server-[ScriptName].ps1
34 | # 400-Database-[ScriptName].ps1
35 | # 500-Table-[ScriptName].ps1
36 | # 600-View-[ScriptName].ps1
37 | # 700-Procedure-[ScriptName].ps1
38 | # 800-Agent-[ScriptName].ps1
39 | # 900-Management-[ScriptName].ps1
40 | ###############################################################################################################
41 |
42 | $configParams = $args[0]
43 | $instance = $configParams["InstanceName"]
44 |
45 | $computerName = $Global:ComputerName
46 | $profileName = "SQLMAIL$computerName"
47 |
48 | $command = "
49 | EXEC sp_configure 'Agent XPs', 1;
50 | RECONFIGURE;
51 | EXEC msdb.dbo.sp_set_sqlagent_properties @email_save_in_sent_folder=1;
52 | EXEC master.dbo.xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'UseDatabaseMail', N'REG_DWORD', 1;
53 | EXEC master.dbo.xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'DatabaseMailProfile', N'REG_SZ', N'$profileName';"
54 |
55 | Execute-SqlCommand -sqlScript $command -sqlInstance $instance
56 |
57 | Write-Log -level "Info" -message "Enabled Agent Notifications for $profileName profile"
58 |
--------------------------------------------------------------------------------
/Examples/_Template.sql:
--------------------------------------------------------------------------------
1 | /* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | /*****************************************************************************************************
4 | * Auto-Install Script Template
5 | *----------------------------------------------------------------------------------------------------
6 | *
7 | * Instructions:
8 | * The top line of this document must contain a commented comma seperated list of the versions of SQL
9 | * that this script applies to. Example: "/* 2000,2005,2008,2008R2 */"
10 | *
11 | * This script template is only suitable for statements that are to be executed as part of the
12 | * auto-install process and must run only against the server instance being installed.
13 | *
14 | * The script must terminate each statement using the ";" operator and must not contain the keyword
15 | * "GO".
16 | *
17 | * This template does not support scripts that need to be called with parameters. If your script
18 | * requires parameters please use the PowerShell Script template.
19 | *
20 | * Scripts must be named using the following pattern:
21 | * level-level name-script name
22 | *
23 | * level: The numeric level of the script. This controls the order in which scripts are applied to
24 | * ensure that dependancies are not broken. See Level list for the possible values.
25 | *
26 | * level name: The friendly name of the level. This is meant to makes the scripts more easily
27 | * identifiable. See Level list for the possible values.
28 | *
29 | * script name: The friendly name of the script. This should be short, but detailed enought to tell
30 | * what the script will accomplish.
31 | *
32 | * Example: "300-Server-AddExtendedProperty.sql" - Server level script that adds the DBA Extended
33 | * property to the master and model databases
34 | *
35 | * Level List:
36 | * ---------------
37 | * 300 - Server - Scripts that create/alter/drop server level objects and settings
38 | * 400 - Database - Scripts that create/alter/drop databases and settings
39 | * 500 - Table - Scripts that create/alter/drop tables, schemas, users, roles
40 | * 600 - View - Scripts that create/alter/drop views, indexes, or other objects with table dependancies
41 | * 700 - Procedure - Scripts that create/alter/drop objects with table/view dependancies
42 | * 800 - Agent - Scripts that create/alter/drop agent jobs, job steps, job schedules, notifications, etc
43 | * 900 - Management - Scripts that are run last that pertain to management of the instance
44 | *****************************************************************************************************/
45 |
46 | /*****************************************************************************************************
47 | * Script Information
48 | *----------------------------------------------------------------------------------------------------
49 | * Author:
50 | * Date:
51 | * Description:
52 | * History:
53 | *****************************************************************************************************/
54 |
--------------------------------------------------------------------------------
/PreScripts/200-Service-Check-AncillaryServices.ps1:
--------------------------------------------------------------------------------
1 | #/* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | ###############################################################################################################
4 | # PowerShell Script Template
5 | ###############################################################################################################
6 | # For use with the Auto-Install process
7 | #
8 | # When called, the script will recieve a single hashtable object passed as a
9 | # parameter. This object contains the following properties:
10 | # $params["SqlVersion"] - Version of SQL being installed (SQL2005, SQL2008, SQL2008R2)
11 | # $params["SqlEdition"] - Edition of SQL being installed (Standard, Enterprise)
12 | # $params["ProcessorArch"] - CPU Architecture (x86, X64)
13 | # $params["InstanceName"] - The name that the instance will be installed with (sqldev1)
14 | # $params["ServiceAccount"] - The name of the account to run the services under (domain\user)
15 | # $params["FilePath"] - path to save the configuration ini file
16 | #
17 | # To add additional parameters - add them to the hashtable passed to the Run-Install function
18 | #
19 | # This script should be placed in the appropriate scripts folder and will be automatically called during the
20 | # auto-install process.
21 | #
22 | # The script should be saved using the following naming convention:
23 | #
24 | # Pre Install Script (Save to PreScripts Folder) -
25 | # -------------------------------------------------
26 | # Pre-100-OS-[ScriptName].ps1
27 | # Pre-200-Service-[ScriptName].ps1
28 | #
29 | # Post Install Script (Save to SQLScripts Folder) -
30 | # -------------------------------------------------
31 | # 100-OS-[ScriptName].ps1
32 | # 200-Service-[ScriptName].ps1
33 | # 300-Server-[ScriptName].ps1
34 | # 400-Database-[ScriptName].ps1
35 | # 500-Table-[ScriptName].ps1
36 | # 600-View-[ScriptName].ps1
37 | # 700-Procedure-[ScriptName].ps1
38 | # 800-Agent-[ScriptName].ps1
39 | ###############################################################################################################
40 |
41 | $configParams = $args[0]
42 |
43 | #Load the script parameters from the config file
44 | [array] $nodes = ($Global:ScriptConfigs | ?{$_.Name -eq "Check-AncillaryServices"}).SelectNodes("Param")
45 | $paramServices = ($nodes | ? {$_.Name -eq "Services"}).Value
46 |
47 | [array] $missing = $nodes | ? {$_.Value -eq ""}
48 | if ($missing.Count -gt 0)
49 | {
50 | return "Script not executed: please check the Run-Install.config file for missing configuration items"
51 | }
52 |
53 | #Split the comma separated list of services into an array
54 | [array] $checks = $paramServices.Split(',')
55 |
56 | #Loop through the array to perform the check
57 | foreach($check in $checks)
58 | {
59 | [array] $services = Get-Service | where{$_.Name -eq $check }| select Name
60 | if ($service.Length > 0)
61 | {
62 | Write-Log -level "Info" -message "$check was found on this server"
63 | }
64 | else
65 | {
66 | Write-Log -level "Info" -message "$check was not found on this server"
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Common/Execute-Sql.ps1:
--------------------------------------------------------------------------------
1 | Function Execute-Sql
2 | {
3 | param
4 | (
5 | [Parameter(Position=0, Mandatory=$true)] [string] $sqlScript,
6 | [Parameter(Position=1, Mandatory=$true)] [AllowEmptyString()] [string] $sqlInstance,
7 | [Parameter(Position=2, Mandatory=$false)] [string] $serverName = $Global:LogicalComputerName,
8 | [Parameter(Position=3, Mandatory=$false)] [string] $databaseName = "master"
9 | )
10 | $scriptName = (Split-Path $sqlScript -Leaf).Split(".")[0]
11 | Write-Log -Level Debug -Message "Looking for params for script: $scriptName"
12 |
13 | [array] $nodes = $Global:ScriptConfigs | ?{$_.Name -eq $scriptName}
14 | if ($nodes)
15 | {
16 | Write-Log -Level Debug -Message "Loading Parameters from Global Config"
17 | $nodes = $nodes.SelectNodes("Param")
18 | foreach ($node in $nodes)
19 | {
20 | Write-Log -Level Debug -Message "$($node.Name) = $($node.Value)"
21 | }
22 | }
23 |
24 |
25 |
26 | $sqlConn = new-Object System.Data.SqlClient.SqlConnection("Server=$serverName\$sqlInstance;DataBase=$databaseName;Integrated Security=SSPI;")
27 |
28 | #### Lets output script output to our log.
29 | $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {param($sender, $event) ($event.Message -split '[\r\n]') |? {Write-Log -level "Info" -message "--------$_" } };
30 | $sqlConn.add_InfoMessage($handler);
31 | $sqlConn.FireInfoMessageEventOnUserErrors = $false;
32 |
33 | $sqlCmd = New-Object System.Data.SqlClient.SqlCommand
34 | $sqlCmd.Connection = $sqlConn
35 | $sqlCmd.CommandType = [System.Data.CommandType]'Text'
36 | $sqlCmd.CommandTimeout = 300
37 | $strCommands = [System.IO.File]::ReadAllText($sqlScript)
38 |
39 | #Look for New Line without Carriage Return and vice versa
40 | $strCommands = $strCommands -replace "`r(?!`n)","`r`n" -replace "`(? nul
17 | if %ERRORLEVEL% == 0 goto RunNonCore
18 |
19 | ver | find "2003" > nul
20 | if %ERRORLEVEL% == 0 goto RunNonCore
21 |
22 | REM *********************************************************************************
23 | REM * Check to see if we are on a Server Core installation
24 | REM *********************************************************************************
25 | FOR /F "tokens=*" %%A IN ('WMIC OS Get OperatingSystemSKU /Value ^| FIND "="') DO (SET %%A)
26 |
27 | REM ECHO OperatingSystemSKU=%OperatingSystemSKU%
28 |
29 | IF %OperatingSystemSKU% gtr 11 IF %OperatingSystemSKU% lss 15 GOTO RunCore
30 | GOTO RunNonCore
31 |
32 |
33 | REM *********************************************************************************
34 | REM * Core - so the PowerShell ISE is not available
35 | REM *********************************************************************************
36 | :RunCore
37 | echo Opening the Start-SqlSpade script using Notepad
38 | powershell.exe -NoProfile "start-process notepad.exe -wait -argumentlist %curr_path% -verb RunAs"
39 | GOTO RunCoreMenu
40 |
41 | REM *********************************************************************************
42 | REM * Core Menu - are you ready to execute the script
43 | REM *********************************************************************************
44 | :RunCoreMenu
45 | echo.
46 | set /p web=Would you like to (R)un the script or (E)xit SPADE?
47 | if "%web%"=="R" goto LaunchScript
48 | if "%web%"=="r" goto LaunchScript
49 | if "%web%"=="L" goto LaunchScriptLogged
50 | if "%web%"=="l" goto LaunchScriptLogged
51 | if "%web%"=="E" goto End
52 | if "%web%"=="e" goto End
53 | echo.
54 | echo Invalid Selection
55 | GOTO RunCoreMenu
56 |
57 | REM *********************************************************************************
58 | REM * Launch the start-sqlspade.ps1 script directly
59 | REM *********************************************************************************
60 | :LaunchScript
61 | echo Running Script...
62 | REM powershell.exe "start-process PowerShell.exe -wait -argumentlist %curr_path% -verb RunAs"
63 | powershell.exe %curr_path%
64 | GOTO End
65 |
66 | REM *********************************************************************************
67 | REM * Launch the start-sqlspade.ps1 script directly with logging
68 | REM *********************************************************************************
69 | :LaunchScriptLogged
70 | echo Running Script...
71 | REM powershell.exe "start-process PowerShell.exe -wait -argumentlist %curr_path% -verb RunAs"
72 | powershell.exe %curr_path% > SetupLog.txt
73 | GOTO End
74 |
75 | REM *********************************************************************************
76 | REM * Not Core - so we have the PowerShell ISE available
77 | REM *********************************************************************************
78 | :RunNonCore
79 | echo Opening the Start-SqlSpade script using PowerShell ISE
80 |
81 | powershell.exe -NoProfile "start-process PowerShell_ISE.exe -argumentlist %curr_path% -verb RunAs"
82 |
83 | REM IF %ERRORLEVEL% NEQ 0 GOTO ErrorNonCore
84 | GOTO End
85 |
86 | REM *********************************************************************************
87 | REM * An error ocurred when trying to launch the ISE
88 | REM *********************************************************************************
89 | :ErrorNonCore
90 | echo Unable to open Start-SqlSpade.ps1 - please verify that the file is present
91 | echo and that the PowerShell ISE is installed then run again
92 | pause
93 |
94 | REM *********************************************************************************
95 | REM * Exit the batch
96 | REM *********************************************************************************
97 | :End
98 | PAUSE
--------------------------------------------------------------------------------
/Common/Invoke-WindowsApi.ps1:
--------------------------------------------------------------------------------
1 | ##############################################################################
2 | ##
3 | ## Invoke-WindowsApi
4 | ##
5 | ## From Windows PowerShell Cookbook (O'Reilly)
6 | ## by Lee Holmes (http://www.leeholmes.com/guide)
7 | ##
8 | ##############################################################################
9 | Function Invoke-WindowsApi
10 | {
11 | <#
12 |
13 | .SYNOPSIS
14 |
15 | Invoke a native Windows API call that takes and returns simple data types.
16 |
17 |
18 | .EXAMPLE
19 |
20 | ## Prepare the parameter types and parameters for the CreateHardLink function
21 | PS >$filename = "c:\temp\hardlinked.txt"
22 | PS >$existingFilename = "c:\temp\link_target.txt"
23 | PS >Set-Content $existingFilename "Hard Link target"
24 | PS >$parameterTypes = [string], [string], [IntPtr]
25 | PS >$parameters = [string] $filename, [string] $existingFilename,
26 | [IntPtr]::Zero
27 |
28 | ## Call the CreateHardLink method in the Kernel32 DLL
29 | PS >$result = Invoke-WindowsApi "kernel32" ([bool]) "CreateHardLink" `
30 | $parameterTypes $parameters
31 | PS >Get-Content C:\temp\hardlinked.txt
32 | Hard Link target
33 |
34 | #>
35 |
36 | param(
37 | ## The name of the DLL that contains the Windows API, such as "kernel32"
38 | [string] $DllName,
39 |
40 | ## The return type expected from Windows API
41 | [Type] $ReturnType,
42 |
43 | ## The name of the Windows API
44 | [string] $MethodName,
45 |
46 | ## The types of parameters expected by the Windows API
47 | [Type[]] $ParameterTypes,
48 |
49 | ## Parameter values to pass to the Windows API
50 | [Object[]] $Parameters
51 | )
52 |
53 | Set-StrictMode -Version Latest
54 |
55 | ## Begin to build the dynamic assembly
56 | $domain = [AppDomain]::CurrentDomain
57 | $name = New-Object Reflection.AssemblyName 'PInvokeAssembly'
58 | $assembly = $domain.DefineDynamicAssembly($name, 'Run')
59 | $module = $assembly.DefineDynamicModule('PInvokeModule')
60 | $type = $module.DefineType('PInvokeType', "Public,BeforeFieldInit")
61 |
62 | ## Go through all of the parameters passed to us. As we do this,
63 | ## we clone the user's inputs into another array that we will use for
64 | ## the P/Invoke call.
65 | $inputParameters = @()
66 | $refParameters = @()
67 |
68 | for($counter = 1; $counter -le $parameterTypes.Length; $counter++)
69 | {
70 | ## If an item is a PSReference, then the user
71 | ## wants an [out] parameter.
72 | if($parameterTypes[$counter - 1] -eq [Ref])
73 | {
74 | ## Remember which parameters are used for [Out] parameters
75 | $refParameters += $counter
76 |
77 | ## On the cloned array, we replace the PSReference type with the
78 | ## .Net reference type that represents the value of the PSReference,
79 | ## and the value with the value held by the PSReference.
80 | $parameterTypes[$counter - 1] =
81 | $parameters[$counter - 1].Value.GetType().MakeByRefType()
82 | $inputParameters += $parameters[$counter - 1].Value
83 | }
84 | else
85 | {
86 | ## Otherwise, just add their actual parameter to the
87 | ## input array.
88 | $inputParameters += $parameters[$counter - 1]
89 | }
90 | }
91 |
92 | ## Define the actual P/Invoke method, adding the [Out]
93 | ## attribute for any parameters that were originally [Ref]
94 | ## parameters.
95 | $method = $type.DefineMethod(
96 | $methodName, 'Public,HideBySig,Static,PinvokeImpl',
97 | $returnType, $parameterTypes)
98 | foreach($refParameter in $refParameters)
99 | {
100 | [void] $method.DefineParameter($refParameter, "Out", $null)
101 | }
102 |
103 | ## Apply the P/Invoke constructor
104 | $ctor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([string])
105 | $attr = New-Object Reflection.Emit.CustomAttributeBuilder $ctor, $dllName
106 | $method.SetCustomAttribute($attr)
107 |
108 | ## Create the temporary type, and invoke the method.
109 | $realType = $type.CreateType()
110 |
111 | $realType.InvokeMember(
112 | $methodName, 'Public,Static,InvokeMethod', $null, $null,$inputParameters)
113 |
114 | ## Finally, go through all of the reference parameters, and update the
115 | ## values of the PSReference objects that the user passed in.
116 | foreach($refParameter in $refParameters)
117 | {
118 | $parameters[$refParameter - 1].Value = $inputParameters[$refParameter - 1]
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/PostScripts/_300-Server-ConfigureDatabaseMail.sql:
--------------------------------------------------------------------------------
1 | /* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | /*****************************************************************************************************
4 | * Auto-Install Script Template
5 | *----------------------------------------------------------------------------------------------------
6 | *
7 | * Instructions:
8 | * The top line of this document must contain a commented comma seperated list of the versions of SQL
9 | * that this script applies to. Example: "/* 2000,2005,2008,2008R2 */"
10 | *
11 | * This script template is only suitable for statements that are to be executed as part of the
12 | * auto-install process and must run only against the server instance being installed.
13 | *
14 | * The script must terminate each statement using the ";" operator and the keyword
15 | * "GO" must be enclosed in square brackets [].
16 | *
17 | * This template does not support scripts that need to be called with parameters. If your script
18 | * requires parameters please use the PowerShell Script template.
19 | *
20 | * Scripts must be named using the following pattern:
21 | * level-level name-script name
22 | *
23 | * level: The numeric level of the script. This controls the order in which scripts are applied to
24 | * ensure that dependancies are not broken. See Level list for the possible values.
25 | *
26 | * level name: The friendly name of the level. This is meant to makes the scripts more easily
27 | * identifiable. See Level list for the possible values.
28 | *
29 | * script name: The friendly name of the script. This should be short, but detailed enought to tell
30 | * what the script will accomplish.
31 | *
32 | * Example: "300-Server-AddExtendedProperty.sql" - Server level script that adds the DBA Extended
33 | * property to the master and model databases
34 | *
35 | * Level List:
36 | * ---------------
37 | * 300 - Server - Scripts that create/alter/drop server level objects and settings
38 | * 400 - Database - Scripts that create/alter/drop databases and settings
39 | * 500 - Table - Scripts that create/alter/drop tables, schemas, users, roles
40 | * 600 - View - Scripts that create/alter/drop views, indexes, or other objects with table dependancies
41 | * 700 - Procedure - Scripts that create/alter/drop objects with table/view dependancies
42 | * 800 - Agent - Scripts that create/alter/drop agent jobs, job steps, job schedules, notifications, etc
43 | * 900 - Management - Scripts that are used for management operations
44 | *****************************************************************************************************/
45 |
46 | /*****************************************************************************************************
47 | * Script Information
48 | *----------------------------------------------------------------------------------------------------
49 | * Author: Michael Wells
50 | * Date: 11/29/2010
51 | * Description: Configure Database Mail and create a default profile
52 | * History: 11/29/2010 - Adapted to Auto-Install script
53 | *
54 | *****************************************************************************************************/
55 |
56 | USE [master];
57 |
58 | -- Enable Database Mail for this instance
59 | EXECUTE sp_configure 'show advanced', 1;
60 | RECONFIGURE;
61 | EXECUTE sp_configure 'Database Mail XPs',1;
62 | RECONFIGURE;
63 | EXECUTE sp_configure 'Agent XPs', 1;
64 | RECONFIGURE;
65 |
66 | declare @servername varchar(40), @email varchar(50)
67 |
68 | select @servername = 'SQLMAIL_' + convert(varchar, serverproperty('machinename'))
69 |
70 | select @email = @servername + '@alfki.com'
71 |
72 | -- Create a Database Mail account
73 | EXECUTE msdb.dbo.sysmail_add_account_sp
74 | @account_name = 'Primary Account',
75 | @description = 'Account used by all mail profiles.',
76 | @email_address = @email,
77 | @replyto_address = 'IT-DBA@alfki.com',
78 | @display_name = @servername,
79 | @mailserver_name = 'mailrelay.alfki.com';
80 |
81 | -- Create a Database Mail profile
82 | EXECUTE msdb.dbo.sysmail_add_profile_sp
83 | @profile_name = @servername,
84 | @description = 'Default public profile for all users';
85 |
86 | -- Add the account to the profile
87 | EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
88 | @profile_name = @servername,
89 | @account_name = 'Primary Account',
90 | @sequence_number = 1;
91 |
92 | -- Grant access to the profile to all msdb database users
93 | EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
94 | @profile_name = @servername,
95 | @principal_name = 'public',
96 | @is_default = 1;
97 |
98 | --EXECUTE msdb.dbo.sysmail_configure_sp
99 | -- 'LoggingLevel', '1' ;
--------------------------------------------------------------------------------
/Examples/PostScripts/300-Server-Set-SsisDbInstance.ps1:
--------------------------------------------------------------------------------
1 | #/* 2005,2008,2008R2,2012,2014,2016 */
2 |
3 | ###############################################################################################################
4 | # PowerShell Script Template
5 | ###############################################################################################################
6 | # For use with the Auto-Install process
7 | #
8 | # When called, the script will recieve a single hashtable object passed as a
9 | # parameter. This object contains the following properties:
10 | # $params["SqlVersion"] - Version of SQL being installed (SQL2005, SQL2008, SQL2008R2)
11 | # $params["SqlEdition"] - Edition of SQL being installed (Standard, Enterprise)
12 | # $params["ProcessorArch"] - CPU Architecture (x86, X64)
13 | # $params["InstanceName"] - The name that the instance will be installed with (sqldev1)
14 | # $params["ServiceAccount"] - The name of the account to run the services under (domain\user)
15 | # $params["FilePath"] - path to save the configuration ini file
16 | #
17 | # To add additional parameters - add them to the hashtable passed to the Run-Install function
18 | #
19 | # This script should be placed in the appropriate scripts folder and will be automatically called during the
20 | # auto-install process.
21 | #
22 | # The script should be saved using the following naming convention:
23 | #
24 | # Pre Install Script (Save to PreScripts Folder) -
25 | # -------------------------------------------------
26 | # Pre-100-OS-[ScriptName].ps1
27 | # Pre-200-Service-[ScriptName].ps1
28 | #
29 | # Post Install Script (Save to SQLScripts Folder) -
30 | # -------------------------------------------------
31 | # 100-OS-[ScriptName].ps1
32 | # 200-Service-[ScriptName].ps1
33 | # 300-Server-[ScriptName].ps1
34 | # 400-Database-[ScriptName].ps1
35 | # 500-Table-[ScriptName].ps1
36 | # 600-View-[ScriptName].ps1
37 | # 700-Procedure-[ScriptName].ps1
38 | # 800-Agent-[ScriptName].ps1
39 | # 900-Management-[ScriptName].ps1
40 | ###############################################################################################################
41 |
42 | ###############################################################################################################################
43 | #
44 | #
"}
222 | "Info" {$string = "$FormattedDate $($_): $messageHtml
"}
223 | "Attention"{$string = "$FormattedDate $($_): $messageHtml*
"}
224 | "Warning" {$string = "$FormattedDate $($_): $messageHtml
"}
225 | "Error" {$string = "$FormattedDate $($_): $messageHtml
"; if ($message -ne "Sample Error"){$Global:CriticalError = $true}}
226 | "Header" {$string = "