DSCResources/MSFT_xSqlServerInstall/MSFT_xSqlServerInstall.psm1

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#
# xSQLServerInstall: DSC resource to install Sql Server Enterprise version.
#

# Controls the default version identifier in paramters.
$DefaultVersionID = "120";

#
# The Get-TargetResource cmdlet.
#
function Get-TargetResource
{
    param
    (   
        [parameter(Mandatory)] 
        [string] $InstanceName = "MSSQLSERVER",
        
        [parameter(Mandatory)] 
        [ValidateNotNullOrEmpty()]
        [string] $SourcePath,

        [PSCredential] $SourcePathCredential,
        
        [string]$VersionID=$DefaultVersionID,

        [string] $Features="SQLEngine,SSMS",

        [PSCredential] $SqlAdministratorCredential,
        
        [bool] $UpdateEnabled = $false,
        [string] $SvcAccount = $NULL,
        [string] $SysAdminAccounts = $NULL,
        [string] $AgentSvcAccount = $NULL,
        [string] $SqlCollation = $NULL,
        [string] $InstallSqlDataDir = $NULL,
        [string] $SqlTempDBDir = $NULL,
        [string] $SqlUserDBDir = $NULL,
        [string] $SqlUserDBLogDir = $NULL, 
        [string] $SqlBackupDir = $NULL
    )

    $list = Get-Service -Name MSSQL*
    $retInstanceName = $null

    if ($InstanceName -eq "MSSQLSERVER")
    {
        if ($list.Name -contains "MSSQLSERVER")
        {
            $retInstanceName = $InstanceName
        }
    }
    elseif ($list.Name -contains $("MSSQL$" + $InstanceName))
    {
        Write-Verbose -Message "SQL Instance $InstanceName is present"
        $retInstanceName = $InstanceName
    }


    $returnValue = @{
        InstanceName = $retInstanceName
    }

    return $returnValue
}


#
# The Set-TargetResource cmdlet.
#
function Set-TargetResource
{
    param
    (   
        [parameter(Mandatory)] 
        [string] $InstanceName = "MSSQLSERVER",
        
        [parameter(Mandatory)] 
        [ValidateNotNullOrEmpty()]
        [string] $SourcePath,

        [PSCredential] $SourcePathCredential,
        
        [string]$VersionID=$DefaultVersionID,
        
        [string] $Features="SQLEngine,SSMS",

        [PSCredential] $SqlAdministratorCredential,
        
        [bool] $UpdateEnabled = $false,
        [string] $SvcAccount = $NULL,
        [string] $SysAdminAccounts = $NULL,
        [string] $AgentSvcAccount = $NULL,
        [string] $SqlCollation = $NULL,
        [string] $InstallSqlDataDir = $NULL,
        [string] $SqlTempDBDir = $NULL,
        [string] $SqlUserDBDir = $NULL,
        [string] $SqlUserDBLogDir = $NULL, 
        [string] $SqlBackupDir = $NULL
    )
    $LogPath = Join-Path $env:SystemDrive -ChildPath "Logs"

    if (!(Test-Path $LogPath))
    {
        New-Item $LogPath -ItemType Directory
    }
    # SQL log from setup cmdline run output
    $logFile = Join-Path $LogPath -ChildPath "sqlInstall-log-$($InstanceName).txt"
    
    # SQL installer path
    $cmd = Join-Path $SourcePath -ChildPath "Setup.exe"

    # TCPENABLED- Specifies the state of the TCP protocol for the SQL Server service.
    # NPENABLED- Specifies the state of the Named Pipes protocol for the SQL Server service
    # tcp/ip and named pipes protocol needs to be enabled for web apps to access db instances. So these are being enabled as a part of default sql server installation
    $cmd += " /Q /ACTION=Install /IACCEPTSQLSERVERLICENSETERMS /IndicateProgress "
    $cmd += " /FEATURES=$Features /INSTANCENAME=$InstanceName "
    
    if ($SqlAdministratorCredential)
    {
        $saPwd = $SqlAdministratorCredential.GetNetworkCredential().Password
        $cmd += " /TCPENABLED=1 /NPENABLED=1 /SECURITYMODE=SQL /SAPWD=$saPwd "
    }
    else
    {
        $cmd += " /TCPENABLED=1 /NPENABLED=1 "
    }
    
    if ($UpdateEnabled)
    {
        $cmd += " /updateEnabled=true "
    }
    else 
    {
        $cmd += " /updateEnabled=false "
    }
    
    if ($SysAdminAccounts)
    {
        $cmd += " /SQLSYSADMINACCOUNTS=$SysAdminAccounts "
    }
    else
    {
        $cmd += " /SQLSYSADMINACCOUNTS=`"builtin\administrators`" "
    }
    
    if ($SvcAccount)
    {
        $cmd += " /SQLSVCACCOUNT=$SvcAccount "
    }
    
    if ($AgentSvcAccount)
    {    
        $cmd += " /AGTSVCACCOUNT=$AgentSvcAccount "
    }
    
    if ($SqlCollation)
    {
        $cmd += " /SQLCOLLATION=$SqlCollation "
    }

    if ($InstallSqlDataDir)
    {
        $cmd += " /INSTALLSQLDATADIR=`"$InstallSqlDataDir`" "
    }

    if ($SqlTempDBDir)
    {
        $cmd += " /SQLTEMPDBDIR=`"$SqlTempDBDir`" /SQLTEMPDBLOGDIR=`"$SqlTempDBDir`" "
    }

    if ($SqlUserDBDir)
    {
        $cmd += " /SQLUSERDBDIR=`"$SqlUserDBDir`" "
    }

    if ($SqlUserDBLogDir)
    {
        $cmd += " /SQLUSERDBLOGDIR=`"$SqlUserDBLogDir`" "
    }

    if ($SqlBackupDir)
    {
        $cmd += " /SQLBACKUPDIR=`"$SqlBackupDir`" "
    }
    
    Write-Verbose "SQL install cmdline: $cmd";

    $cmd += " > $logFile 2>&1 "

    NetUse -SharePath $SourcePath -SharePathCredential $SourcePathCredential -Ensure "Present";
    
    # check that the sourcepath exists
    Write-Verbose "Validating access to $SourcePath";
    if (!(Test-Path $SourcePath))
    {
        # Throw an error message indicating SQL Server install media is not valid
        $errorId = "InstallMediaNotFound";
        $exceptionStr = "SQL Server install media path was not found.";
        $errorCategory = [System.Management.Automation.ErrorCategory]::ObjectNotFound;
        $exception = New-Object System.InvalidOperationException $exceptionStr; 
        $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $null;

        $PSCmdlet.ThrowTerminatingError($errorRecord);
    }
    try
    {
        Invoke-Expression $cmd
    }
    finally
    {
        NetUse -SharePath $SourcePath -SharePathCredential $SourcePathCredential -Ensure "Absent"
    }
    # Check the SQL logs for installation status.
    $installStatus = $false
    try
    {        
        # SQL Server log folder
        $LogPath = Join-Path $env:ProgramFiles "Microsoft SQL Server\$VersionID\Setup Bootstrap\Log"
        $sqlLog = Get-Content "$LogPath\summary.txt"
        if($sqlLog -ne $null)
        {
            $message = $sqlLog | fl
            if($message -ne $null)
            {
                # sample report when the install is succesful
                # Overall summary:
                # Final result: Passed
                # Exit code (Decimal): 0
                $finalResult = $message[1] | Out-String     
                $exitCode = $message[2] | Out-String    

                if(($finalResult.Contains("Passed") -eq $True) -and ($exitCode.Contains("0") -eq $True))
                {                     
                    $installStatus = $true
                }                
             }
        }
    }
    catch
    {
        Write-Verbose "SQL Installation did not succeed."
    }
    if($installStatus -eq $true)
    {
        # Tell the DSC Engine to restart the machine
        $global:DSCMachineStatus = 1
    }
    else    
    {        
        # Throw an error message indicating failure to install SQL Server install
        $errorId = "InValidSQLServerInstall";
        $exceptionStr = "SQL Server installation did not succeed. For more details please refer to the logs under $LogPath folder."
        $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult;
        $exception = New-Object System.InvalidOperationException $exceptionStr; 
        $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $null

        $PSCmdlet.ThrowTerminatingError($errorRecord);
     }
}
#
# The Test-TargetResource cmdlet.
#
function Test-TargetResource
{
    param
    (   
        [parameter(Mandatory)] 
        [string] $InstanceName = "MSSQLSERVER",
        
        [parameter(Mandatory)] 
        [ValidateNotNullOrEmpty()]
        [string] $SourcePath,

        [PSCredential] $SourcePathCredential,
        
        [string]$VersionID=$DefaultVersionID,

        [string] $Features="SQLEngine,SSMS",

        [PSCredential] $SqlAdministratorCredential,

        [bool] $UpdateEnabled = $false,
        [string] $SvcAccount = $NULL,
        [string] $SysAdminAccounts = $NULL,
        [string] $AgentSvcAccount = $NULL,
        [string] $SqlCollation = $NULL,
        [string] $InstallSqlDataDir = $NULL,
        [string] $SqlTempDBDir = $NULL,
        [string] $SqlUserDBDir = $NULL,
        [string] $SqlUserDBLogDir = $NULL, 
        [string] $SqlBackupDir = $NULL
    )

    $info = Get-TargetResource -InstanceName $InstanceName -SourcePath $SourcePath -SqlAdministratorCredential $SqlAdministratorCredential
    
    return ($info.InstanceName -eq $InstanceName)
}



function NetUse
{
    param
    (   
        [parameter(Mandatory)] 
        [ValidateNotNullOrEmpty()]
        [string] $SharePath,
        
        [PSCredential]$SharePathCredential,
        
        [string] $Ensure = "Present"
    )

    if ($null -eq $SharePathCredential)
    {
        return;
    }

    Write-Verbose -Message "NetUse set share $SharePath ..."

    if ($Ensure -eq "Absent")
    {
        $cmd = "net use $SharePath /DELETE"
    }
    else 
    {
        $cred = $SharePathCredential.GetNetworkCredential()
        $pwd = $cred.Password 
        $user = $cred.Domain + "\" + $cred.UserName
        $cmd = "net use $SharePath $pwd /user:$user"
    }

    Invoke-Expression $cmd
}

Export-ModuleMember -Function *-TargetResource