AutomatedLabScom.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
function Install-LabScom
{
    [CmdletBinding()]
    param ( )

    Write-LogFunctionEntry

    # defaults
    $iniManagementServer = @{
        ManagementGroupName           = 'SCOM2019'
        SqlServerInstance             = ''
        SqlInstancePort               = '1433'
        DatabaseName                  = 'OperationsManager'
        DwSqlServerInstance           = ''
        InstallLocation               = 'C:\Program Files\{0}'
        DwSqlInstancePort             = '1433'
        DwDatabaseName                = 'OperationsManagerDW'
        ActionAccountUser             = 'OM19AA'
        ActionAccountPassword         = ''
        DASAccountUser                = 'OM19DAS' 
        DASAccountPassword            = ''
        DataReaderUser                = 'OM19READ'
        DataReaderPassword            = ''
        DataWriterUser                = 'OM19WRITE'
        DataWriterPassword            = ''
        EnableErrorReporting          = 'Never'
        SendCEIPReports               = '0'
        UseMicrosoftUpdate            = '0'
        AcceptEndUserLicenseAgreement = '1'
        ProductKey                    = ''        
    }

    $iniAddManagementServer = @{
        SqlServerInstance             = ''
        SqlInstancePort               = '1433'
        DatabaseName                  = 'OperationsManager'
        InstallLocation               = 'C:\Program Files\{0}'
        ActionAccountUser             = 'OM19AA'
        ActionAccountPassword         = ''
        DASAccountUser                = 'OM19DAS' 
        DASAccountPassword            = ''
        DataReaderUser                = 'OM19READ'
        DataReaderPassword            = ''
        DataWriterUser                = 'OM19WRITE'
        DataWriterPassword            = ''
        EnableErrorReporting          = 'Never'
        SendCEIPReports               = '0'
        AcceptEndUserLicenseAgreement = '1'
        UseMicrosoftUpdate            = '0'
    }

    $iniNativeConsole = @{
        EnableErrorReporting          = 'Never'
        InstallLocation               = 'C:\Program Files\{0}'
        SendCEIPReports               = '0'
        UseMicrosoftUpdate            = '0'
        AcceptEndUserLicenseAgreement = '1'
    }

    $iniWebConsole = @{
        ManagementServer              = ''
        WebSiteName                   = 'Default Web Site'
        WebConsoleAuthorizationMode   = 'Mixed'
        SendCEIPReports               = '0'
        UseMicrosoftUpdate            = '0'
        AcceptEndUserLicenseAgreement = '1'
    }

    $iniReportServer = @{
        ManagementServer              = ''
        SRSInstance                   = ''
        DataReaderUser                = 'OM19READ'
        DataReaderPassword            = ''
        SendODRReports                = '0'
        UseMicrosoftUpdate            = '0'
        AcceptEndUserLicenseAgreement = '1'
    }
    
    $lab = Get-Lab
    $all = Get-LabVM -Role Scom
    $scomConsoleRole = Get-LabVM -Role ScomConsole
    $scomManagementServer = Get-LabVm -Role ScomManagement
    $firstmgmt = $scomManagementServer | Select-Object -First 1
    $addtlmgmt = $scomManagementServer | Select-Object -Skip 1
    $scomWebConsoleRole = Get-LabVM -Role ScomWebConsole
    $scomReportingServer = Get-LabVm -Role ScomReporting

    Start-LabVM -ComputerName $all -Wait

    # Prerequisites, all
    $odbc = Get-LabConfigurationItem -Name SqlOdbc13
    $SQLSysClrTypes = Get-LabConfigurationItem -Name SqlClrType2014
    $ReportViewer = Get-LabConfigurationItem -Name ReportViewer2015
    $odbcFile = Get-LabInternetFile -Uri $odbc -Path $labsources\SoftwarePackages -FileName odbc.msi -PassThru
    $SQLSysClrTypesFile = Get-LabInternetFile -uri $SQLSysClrTypes -Path $labsources\SoftwarePackages -FileName SQLSysClrTypes.msi -PassThru
    $ReportViewerFile = Get-LabInternetFile -uri $ReportViewer -Path $labsources\SoftwarePackages -FileName ReportViewer.msi -PassThru
    Install-LabSoftwarePackage -Path $odbcFile.FullName -ComputerName $all -CommandLine '/QN ADDLOCAL=ALL IACCEPTMSODBCSQLLICENSETERMS=YES /L*v C:\odbc.log' -NoDisplay
    
    if (Get-LabVm -Role ScomConsole, ScomWebConsole)
    {
        Install-LabSoftwarePackage -path $SQLSysClrTypesFile.FullName -ComputerName (Get-LabVm -Role ScomConsole, ScomWebConsole) -CommandLine '/quiet /norestart /log C:\DeployDebug\SQLSysClrTypes.log' -NoDisplay
        Install-LabSoftwarePackage -path $ReportViewerFile.FullName -ComputerName (Get-LabVm -Role ScomConsole, ScomWebConsole) -CommandLine '/quiet /norestart /log C:\DeployDebug\ReportViewer.log' -NoDisplay
        Install-LabWindowsFeature -Computername (Get-LabVm -Role ScomConsole, ScomWebConsole) NET-WCF-HTTP-Activation45, Web-Static-Content, Web-Default-Doc, Web-Dir-Browsing, Web-Http-Errors, Web-Http-Logging, Web-Request-Monitor, Web-Filtering, Web-Stat-Compression, Web-Mgmt-Console, Web-Metabase, Web-Asp-Net, Web-Windows-Auth  -NoDisplay
    }

    if ($scomReportingServer)
    {
        Invoke-LabCommand -ComputerName $scomReportingServer -ScriptBlock {
            Get-Service -Name SQLSERVERAGENT* | Set-Service -StartupType Automatic -Status Running
        } -NoDisplay
    }

    # Extract SCOM on all machines
    $scomIso = ($lab.Sources.ISOs | Where-Object { $_.Name -like 'Scom*' }).Path
    $isos = Mount-LabIsoImage -ComputerName $all -IsoPath $scomIso -SupressOutput -PassThru
    Invoke-LabCommand -ComputerName $all -Variable (Get-Variable isos) -ActivityName 'Extracting SCOM Server' -ScriptBlock {
        $setup = Get-ChildItem -Path $($isos.Where( { $_.InternalComputerName -eq $env:COMPUTERNAME })).DriveLetter -Filter *.exe | Select-Object -First 1
        Start-Process -FilePath $setup.FullName -ArgumentList '/VERYSILENT', '/DIR=C:\SCOM' -Wait
    } -NoDisplay
    
    # Server
    $jobs = foreach ($vm in $firstmgmt)
    {
        $iniManagement = $iniManagementServer.Clone()
        $role = $vm.Roles | Where-Object Name -eq ScomManagement

        foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*Password' }))
        {
            $iniManagement[$kvp.Key] = $vm.GetCredential((Get-Lab)).GetNetworkCredential().Password # Default lab credential
        }

        foreach ($property in $role.Properties.GetEnumerator())
        {
            if (-not $iniManagement.ContainsKey($property.Key)) { continue }
            $iniManagement[$property.Key] = $property.Value
        }

        if ($role.Properties.ContainsKey('ProductKey'))
        {
            $iniServer['ProductKey'] = $role.Properties['ProductKey']
        }

        # Create users/groups
        Invoke-LabCommand -ComputerName (Get-LabVm -Role RootDc | Select-Object -First 1) -ScriptBlock {
            foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*User' }))
            {
                if ($kvp.Key -like '*User')
                {
                    $userName = $kvp.Value
                    $password = $iniManagement[($kvp.Key -replace 'User', 'Password')]
                }
                $userAccount = $null # Damn AD cmdlets.

                try
                {
                    $userAccount = Get-ADUser -Identity $userName -ErrorAction Stop
                }
                catch
                { }

                if (-not $userAccount)
                {
                    $userAccount = New-ADUser -Name $userName -SamAccountName $userName -PassThru -Enabled $true -AccountPassword ($password | ConvertTo-SecureString -AsPlainText -Force)
                }
            }

            $group = $iniManagement['ScomAdminGroupName']
            if (-not $group) { return }
            try
            {
                $group = Get-ADGroup -Identity $group -ErrorAction Stop
            }
            catch {}
            if (-not $group)
            {
                New-ADGroup -Name $group -GroupScope Global -GroupType Security
            }
        } -Variable (Get-Variable iniManagement) -NoDisplay

        foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*User' }))
        {
            if ($kvp.Value.Contains('\')) { continue }
            
            $iniManagement[$kvp.Key] = '{0}\{1}' -f $vm.DomainAccountName.Split('\')[0], $kvp.Value
        }
        
        if ($iniManagement['SqlServerInstance'] -like '*\*')
        {
            $sqlMachineName = $iniManagement['SqlServerInstance'].Split('\')[0]
            $sqlMachine = Get-LabVm -ComputerName $sqlMachineName
        }

        if ($iniManagement['DwSqlServerInstance'] -like '*\*')
        {
            $sqlDwMachineName = $iniManagement['DwSqlServerInstance'].Split('\')[0]
            $sqlDwMachine = Get-LabVm -ComputerName $sqlDwMachineName
        }

        if (-not $sqlMachine)
        {
            $sqlMachine = Get-LabVm -Role SQLServer2016, SQLServer2017 | Select-Object -First 1
        }

        if (-not $sqlDwMachine)
        {
            $sqlDwMachine = Get-LabVm -Role SQLServer2016, SQLServer2017 | Select-Object -First 1
        }

        if ([string]::IsNullOrWhiteSpace($iniManagement['SqlServerInstance']))
        {
            $iniManagement['SqlServerInstance'] = $sqlMachine.Name
        }
        if ([string]::IsNullOrWhiteSpace($iniManagement['DwSqlServerInstance']))
        {
            $iniManagement['DwSqlServerInstance'] = $sqlMachine.Name
        }

         # Setup Command Line Management-Server
            
            Invoke-LabCommand -ComputerName $vm -ScriptBlock {
            Add-LocalGroupMember -Sid S-1-5-32-544 -Member $iniManagement['DASAccountUser']
            } -Variable (Get-Variable iniManagement)
            $CommandlineArgumentsServer = $iniManagement.GetEnumerator() | Where-Object Key -notin ProductKey, ScomAdminGroupName | ForEach-Object { '/{0}:"{1}"' -f $_.Key, $_.Value }
            
            $setupCommandlineServer = "/install /silent /components:OMServer $CommandlineArgumentsServer"
            Install-LabSoftwarePackage -ComputerName $vm -LocalPath C:\SCOM\setup.exe -CommandLine $setupCommandlineServer -AsJob -PassThru -UseShellExecute -UseExplicitCredentialsForScheduledJob -AsScheduledJob -Timeout 20 -NoDisplay
            $isPrimaryManagementServer = $isPrimaryManagementServer - 1
        
    }

    
    if ($jobs) { Wait-LWLabJob -Job $jobs }

    $jobs = foreach ($vm in $addtlmgmt)
    {
        $iniManagement = $iniAddManagementServer.Clone()
        $role = $vm.Roles | Where-Object Name -eq ScomManagement

        foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*Password' }))
        {
            $iniManagement[$kvp.Key] = $vm.GetCredential((Get-Lab)).GetNetworkCredential().Password # Default lab credential
        }

        foreach ($property in $role.Properties.GetEnumerator())
        {
            if (-not $iniManagement.ContainsKey($property.Key)) { continue }
            $iniManagement[$property.Key] = $property.Value
        }

        if ($role.Properties.ContainsKey('ProductKey'))
        {
            $iniServer['ProductKey'] = $role.Properties['ProductKey']
        }

        foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*User' }))
        {
            if ($kvp.Value.Contains('\')) { continue }
            
            $iniManagement[$kvp.Key] = '{0}\{1}' -f $vm.DomainAccountName.Split('\')[0], $kvp.Value
        }
        
        if ($iniManagement['SqlServerInstance'] -like '*\*')
        {
            $sqlMachineName = $iniManagement['SqlServerInstance'].Split('\')[0]
            $sqlMachine = Get-LabVm -ComputerName $sqlMachineName
        }

        if ($iniManagement['DwSqlServerInstance'] -like '*\*')
        {
            $sqlDwMachineName = $iniManagement['DwSqlServerInstance'].Split('\')[0]
            $sqlDwMachine = Get-LabVm -ComputerName $sqlDwMachineName
        }

        if (-not $sqlMachine)
        {
            $sqlMachine = Get-LabVm -Role SQLServer2016, SQLServer2017 | Select-Object -First 1
        }

        if (-not $sqlDwMachine)
        {
            $sqlDwMachine = Get-LabVm -Role SQLServer2016, SQLServer2017 | Select-Object -First 1
        }

        if ([string]::IsNullOrWhiteSpace($iniManagement['SqlServerInstance']))
        {
            $iniManagement['SqlServerInstance'] = $sqlMachine.Name
        }
        if ([string]::IsNullOrWhiteSpace($iniManagement['DwSqlServerInstance']))
        {
            $iniManagement['DwSqlServerInstance'] = $sqlMachine.Name
        }

        
            # Setup Command Line Management-Server
            Invoke-LabCommand -ComputerName $vm -ScriptBlock {
            Add-LocalGroupMember -Sid S-1-5-32-544 -Member $iniManagement['DASAccountUser']
            } -Variable (Get-Variable iniManagement)
            $CommandlineArgumentsServer = $iniManagement.GetEnumerator() | Where-Object Key -notin ProductKey, ScomAdminGroupName | ForEach-Object { '/{0}:"{1}"' -f $_.Key, $_.Value }
            
            $setupCommandlineServer = "/install /silent /components:OMServer $CommandlineArgumentsServer"
            Install-LabSoftwarePackage -ComputerName $vm -LocalPath C:\SCOM\setup.exe -CommandLine $setupCommandlineServer -AsJob -PassThru -UseShellExecute -UseExplicitCredentialsForScheduledJob -AsScheduledJob -Timeout 20 -NoDisplay
        
    }

    # After SCOM is set up, we need to wait a bit for it to "settle", otherwise there might be timing issues later on
    Start-Sleep -Seconds 30
    Remove-LabPSSession -ComputerName $firstmgmt
    $cmdAvailable = Invoke-LabCommand -PassThru -NoDisplay -ComputerName $firstmgmt {Get-Command Get-ScomManagementServer -ErrorAction SilentlyContinue}
    if (-not $cmdAvailable)
    {
        Start-Sleep -Seconds 30
        Remove-LabPSSession -ComputerName $firstmgmt
    }

    Invoke-LabCommand -ComputerName $firstmgmt -ActivityName 'Waiting for SCOM Management to get in gear' -ScriptBlock {
        $start = Get-Date
        do
        {
            Start-Sleep -Seconds 10
            if ((Get-Date).Subtract($start) -gt '00:05:00') { throw 'SCOM startup not finished after 5 minutes' }
        }
        until (Get-ScomManagementServer -ErrorAction SilentlyContinue)
    }

    # Licensing
    foreach ($vm in $firstmgmt)
    {
        $role = $vm.Roles | Where-Object Name -eq ScomManagement
        if (-not $role.Properties.ContainsKey('ProductKey')) { continue }
        if ([string]::IsNullOrWhiteSpace($role.Properties['ProductKey'])) { continue }
        $productKey = $role.Properties['ProductKey']
 
        Invoke-LabCommand -ComputerName $vm -Variable (Get-Variable -Name productKey) -ScriptBlock {
            Set-SCOMLicense -ProductId $productKey
        } -NoDisplay
    }

    $jobs = foreach ($vm in $scomConsoleRole)
    {
        $iniConsole = $iniNativeConsole.Clone()
        $role = $vm.Roles | Where-Object Name -in ScomConsole
        
        foreach ($property in $role.Properties.GetEnumerator())
        {
            if (-not $iniConsole.ContainsKey($property.Key)) { continue }
            $iniConsole[$property.Key] = $property.Value
        }

        $CommandlineArgumentsNativeConsole = $iniNativeConsole.GetEnumerator() | ForEach-Object { '/{0}:"{1}"' -f $_.Key, $_.Value }
        $setupCommandlineNativeConsole = "/install /silent /components:OMConsole $CommandlineArgumentsNativeConsole"

        Install-LabSoftwarePackage -ComputerName $vm -LocalPath C:\SCOM\setup.exe -CommandLine $setupCommandlineNativeConsole -AsJob -PassThru -UseShellExecute -UseExplicitCredentialsForScheduledJob -AsScheduledJob -Timeout 20 -NoDisplay
    }

    if ($jobs) { Wait-LWLabJob -Job $jobs }

    $jobs = foreach ($vm in $scomWebConsoleRole)
    {
        $iniWeb = $iniWebConsole.Clone()
        $role = $vm.Roles | Where-Object Name -in ScomWebConsole
        foreach ($property in $role.Properties.GetEnumerator())
        {
            if (-not $iniWeb.ContainsKey($property.Key)) { continue }
            $iniWeb[$property.Key] = $property.Value
        }

        if (-not [string]::IsNullOrWhiteSpace($iniWeb['ManagementServer']))
        {
            $mgtMachineName = $iniWeb['ManagementServer']
            $mgtMachine = Get-LabVm -ComputerName $mgtMachineName
        }

        if (-not $mgtMachine)
        {
            $mgtMachine = Get-LabVm -Role ScomManagement | Select-Object -First 1
        }

        if ([string]::IsNullOrWhiteSpace($iniWeb['ManagementServer']))
        {
            $iniWeb['ManagementServer'] = $mgtMachine.Name
        }

        $CommandlineArgumentsWebConsole = $iniWeb.GetEnumerator() | ForEach-Object { '/{0}:"{1}"' -f $_.Key, $_.Value }
        $setupCommandlineWebConsole = "/install /silent /components:OMWebConsole $commandlineArgumentsWebConsole"

        Install-LabSoftwarePackage -ComputerName $vm -LocalPath C:\SCOM\setup.exe -CommandLine $setupCommandlineWebConsole -AsJob -PassThru -UseShellExecute -UseExplicitCredentialsForScheduledJob -AsScheduledJob -Timeout 20 -NoDisplay
    }

    if ($jobs) { Wait-LWLabJob -Job $jobs }

    $jobs = foreach ($vm in $scomReportingServer)
    {
        $iniReport = $iniReportServer.Clone()
        $role = $vm.Roles | Where-Object Name -in ScomReporting

        foreach ($property in $role.Properties.GetEnumerator())
        {
            if (-not $iniReport.ContainsKey($property.Key)) { continue }
            $iniReport[$property.Key] = $property.Value
        }

        if (-not [string]::IsNullOrWhiteSpace($iniReport['ManagementServer']))
        {
            $mgtMachineName = $iniReport['ManagementServer']
            $mgtMachine = Get-LabVm -ComputerName $mgtMachineName
        }

        if (-not $mgtMachine)
        {
            $mgtMachine = Get-LabVm -Role ScomManagement | Select-Object -First 1
        }

        if ([string]::IsNullOrWhiteSpace($iniReport['ManagementServer']))
        {
            $iniReport['ManagementServer'] = $mgtMachine.Name
        }

        if (-not [string]::IsNullOrWhiteSpace($iniReport['SRSInstance']))
        {
            $ssrsName = $iniReport['SRSInstance'].Split('\')[0]
            $ssrsVm = Get-LabVm -ComputerName $ssrsName
        }

        if (-not $ssrsVm)
        {
            $ssrsVm = Get-LabVm -Role SQLServer2016, SQLServer2017 | Select-Object -First 1
        }

        if ([string]::IsNullOrWhiteSpace($iniReport['SRSInstance']))
        {
            $iniReport['SRSInstance'] = "$ssrsVm\SSRS"
        }

        if ([string]::IsNullOrWhiteSpace($iniReport['DataReaderPassword']))
        {
            $iniReport['DataReaderPassword'] = $vm.GetCredential($lab).GetNetworkCredential().Password
        }

        Invoke-LabCommand -ComputerName (Get-LabVm -Role RootDc | Select-Object -First 1) -ScriptBlock {
            foreach ($kvp in $iniManagement.GetEnumerator().Where( { $_.Key -like '*User' }))
            {
                if ($kvp.Key -like '*User')
                {
                    $userName = $kvp.Value
                    $password = $iniManagement[($kvp.Key -replace 'User', 'Password')]
                }
                $userAccount = $null # Damn AD cmdlets.

                try
                {
                    $userAccount = Get-ADUser -Identity $userName -ErrorAction Stop
                }
                catch
                { }

                if (-not $userAccount)
                {
                    $userAccount = New-ADUser -Name $userName -SamAccountName $userName -PassThru -Enabled $true -AccountPassword ($password | ConvertTo-SecureString -AsPlainText -Force)
                }

            }
        } -Variable (Get-Variable iniReport) -NoDisplay

        if (-not $iniReport['DataReaderUser'].Contains('\'))
        {
            $iniReport['DataReaderUser'] = '{0}\{1}' -f $vm.DomainAccountName.Split('\')[0], $iniReport['DataReaderUser']
        }

        $CommandlineArgumentsReportServer = $iniReport.GetEnumerator() | ForEach-Object { '/{0}:"{1}"' -f $_.Key, $_.Value }
        $setupCommandlineReportServer = "/install /silent /components:OMReporting $commandlineArgumentsReportServer"
        Invoke-LabCommand -ComputerName $scomReportingServer -ScriptBlock {
            Get-Service -Name SQLSERVERAGENT* | Set-Service -StartupType Automatic -Status Running
        } -NoDisplay

        Install-LabSoftwarePackage -ComputerName $vm -LocalPath C:\SCOM\setup.exe -CommandLine $setupCommandlineReportServer -AsJob -PassThru -UseShellExecute -UseExplicitCredentialsForScheduledJob -AsScheduledJob -Timeout 20 -NoDisplay
    }

    if ($jobs) { Wait-LWLabJob -Job $jobs }

    Write-LogFunctionExit
}