1+ $Error.Clear ()
2+
3+ # Create output directory if not exists
4+
5+ $outDir = ' /var/opt/mssql/log/assessments'
6+ if (-not ( Test-Path $outDir )) { mkdir $outDir }
7+ $outPath = Join-Path $outDir ' assessment-latest'
8+
9+ $errorPath = Join-Path $outDir ' assessment-latest-errors'
10+ if ( Test-Path $errorPath ) { remove-item $errorPath }
11+
12+ function ConvertTo-LogOutput {
13+ [CmdletBinding ()]
14+ param (
15+ [Parameter (ValueFromPipeline = $true )]
16+ $input
17+ )
18+ process {
19+ switch ($input ){
20+ { $_ -is [System.Management.Automation.WarningRecord ] }{
21+ $result = @ {
22+ ' TimeStamp' = $ (Get-Date ).ToString(" O" );
23+ ' Warning' = $_.Message
24+ }
25+ }
26+ default {
27+ $result = @ {
28+ ' TimeStamp' = $input.TimeStamp ;
29+ ' Severity' = $input.Severity ;
30+ ' TargetType' = $input.TargetType ;
31+ ' ServerName' = $serverName ;
32+ ' HostName' = $hostName ;
33+ ' TargetName' = $input.TargetObject.Name ;
34+ ' TargetPath' = $input.TargetPath ;
35+ ' CheckId' = $input.Check.Id ;
36+ ' CheckName' = $input.Check.DisplayName ;
37+ ' Message' = $input.Message ;
38+ ' RulesetName' = $input.Check.OriginName ;
39+ ' RulesetVersion' = $input.Check.OriginVersion.ToString ();
40+ ' HelpLink' = $input.HelpLink
41+ }
42+
43+ if ( $input.TargetType -eq ' Database' ) {
44+ $result [' AvailabilityGroup' ] = $input.TargetObject.AvailabilityGroupName
45+ }
46+ }
47+ }
48+
49+ $result
50+ }
51+ }
52+
53+ function Get-TargetsRecursive {
54+
55+ [CmdletBinding ()]
56+ Param (
57+ [Parameter (ValueFromPipeline = $true )]
58+ [Microsoft.SqlServer.Management.Smo.Server ] $server
59+ )
60+
61+ $server
62+ $server.Databases
63+ }
64+
65+ try {
66+ $login , $pwd = Get-Content ' /var/opt/mssql/secrets/assessment' - Encoding UTF8NoBOM - TotalCount 2
67+ $securePassword = ConvertTo-SecureString $pwd - AsPlainText - Force
68+ $credential = New-Object System.Management.Automation.PSCredential ($login , $securePassword )
69+
70+ $serverName = (Invoke-SqlCmd - ServerInstance . - Credential $credential - Query " SELECT @@SERVERNAME" )[0 ]
71+ $hostName = (Invoke-SqlCmd - ServerInstance . - Credential $credential - Query " SELECT HOST_NAME()" )[0 ]
72+
73+ # Invoke assessment and store results.
74+ # Replace 'ConvertTo-Json' with 'ConvertTo-Csv' to change output format.
75+ # Available output formats: JSON, CSV, XML.
76+ # Encoding parameter is optional.
77+
78+ Get-SqlInstance - ServerInstance . - Credential $credential - ErrorAction Stop
79+ | Get-TargetsRecursive
80+ | Invoke-SqlAssessment 3>&1
81+ | ConvertTo-LogOutput
82+ | ConvertTo-Json - AsArray
83+ | Set-Content $outPath - Encoding UTF8NoBOM
84+ }
85+ finally {
86+ if ($Error ) {
87+ $Error
88+ | ForEach-Object { @ { ' TimeStamp' = $ (Get-Date ).ToString(" O" ); ' Message' = $_.ToString () } }
89+ | ConvertTo-Json - AsArray
90+ | Set-Content $errorPath - Encoding UTF8NoBOM
91+ }
92+ }
0 commit comments