Contents
Introduction to EPM Framework. 2
1. Set up Central Management Server. 3
2. Configure/Create Policies and Centralize on the Central Management Server. 4
3. Create Database and Database Objects To Store Policy Evaluation Results. 6
4. Configure PowerShell Script. 7
5. Test the PowerShell Script. 8
6. Create SQL Server Agent Job to Automate Execution of Policy Evaluation.. 9
7. Deploy Reports to SQL Server Reporting Services. 11
Appendix A: Additional Considerations. 15
Appendix B: Database Objects. 17
Appendix C: Upgrade from previous version.. 18
Introduction to EPM Framework
The Enterprise Policy Management Framework (EPM) is a solution to extend SQL Server Policy-Based Management to all versions of SQL Server in an enterprise, including SQL Server 2000 and SQL Server 2005. The EPM Framework will report the state of specified SQL Server instances against policies that define intent, desired configuration, and deployment standards.
When the Enterprise Policy Management Framework (EPM) is implemented, policies will be evaluated against specified instances of SQL Server through PowerShell. This solution will require at least one instance of SQL Server 2008. The PowerShell script will run from this instance through a SQL Server Agent job or manually through the PowerShell interface. The PowerShell script will capture the policy evaluation output and insert the output to a SQL Server table. SQL Server Reporting Services (2008 or above) reports will deliver information from the centralized table.
This solution requires the following components to be configured in your environment. All SQL Server requirements listed below may be executed from and managed on the same instance:
- SQL Server (2008 or above) instance to store policies
- SQL Server (2008 or above) instance to act as the Central Management Server
- SQL Server (2008 or above) instance to execute the PowerShell script
- SQL Server management database to archive policy evaluation results
- SQL Server (2008 or above) Reporting Services to render and deliver policy history reports
Please refer to Microsoft documentation (Features Supported by the Editions of SQL Server) to determine the appropriate editions to support central management server, policy evaluation, SQL Server Agent, and Reporting Services. All components are supported on SQL Server Enterprise and SQL Server Standard.
This document identifies the steps to configure the Enterprise Policy Management Framework objects in a SQL Server environment.
The EPM Framework requires an instance of SQL Server (2008 or above) designated as a Central Management Server (CMS). The CMS will manage the logical groups of servers. The names of the logical groups are passed into variables in the Enterprise Policy Management Framework for policy evaluation against these groups.
If an instance has not yet been designated as a Central Management Server, execute the following steps:
- Open SQL Server Management Studio. Select the View menu. Click Registered Servers.
- In Registered Servers, expand Database Engine, right-click Central Management Servers, point to New, and then click Central Management Servers.
- In the New Server Registration dialog box, register the instance of SQL Server that you want to become the Central Management Server.
After a SQL Server (2008 or above) instance has been designated as a CMS, create the logical server groups and register SQL Server instances into these logical server group. SQL Server Books Online details the manual steps to register instances into logical server groups: Create a Central Management Server and Server Group. Figure 1 is an example of a Central Management Server (individual server groups and registered instances will differ based on each environment).
Figure 1
All policies that will be evaluated using the EPM framework will be stored and managed on the SQL Server instance defined as the Central Management Server. The PowerShell script will loop through these policies during execution.
Policies stored on the Central Management Server should be configured to improve execution scale and minimize/eliminate false policy failures. The following are best practices for designing policies to scale with the EPM Framework.
Categorize policies
The EPM framework PowerShell script must be given a parameter for policy category (example: Microsoft Best Practices: Performance). Therefore all policies should be placed in a category to enable a scalable solution for policy evaluation over a large environment.
Ensure all policies are configured with appropriate server restrictions and defined targets.
Policies may not be relevant for all versions and/or editions of SQL Server. For example, a policy which checks that a database is enabled for Transparent Data Encryption will not be relevant on SQL Server 2000 or SQL Server 2005, or SQL Server 2008 editions other than Enterprise. Furthermore, this policy may not be relevant for every database on an instance. A policy that checks for existing number of data files might be more relevant for tempDB only. Define server restrictions on polices to eliminate evaluation failures due to incompatible editions. Define targets on polices to eliminate false failures for databases which are not relevant to the policy.
If at a given point in time you choose to stop collecting for a specific policy that belonged to a category YY, instead of just deleting that policy (which would not clear its previous result from the reports), we recommend you move it to a new category named “Disabled”, which you would not be collecting results on that category in any job. This way, not only will you keep the policy should you choose to use it again, but also the reports will exclude that specific category and any policies inside, including historic data on any policy inside that “Disabled” category.
Environments may wish to leverage the Best Practices Policies which are installed with SQL Server (Figure 2 below shows the SQL Server 2012 Policies setup) or available from the SQL Server 2008 R2 Feature Pack. If installed already, these policies may be imported to the Central Management Server – for example, SQL Server 2012 includes pre-configured best practice policies typically located at C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Policies\DatabaseEngine\1033. For further information on this topic, see How to: Export and Import a Policy-Based Management Policy.
Figure 2
If you choose to import these policies, you may want to run the script PBM_Fix_ImportedPolicies.sql afterwards for some needed actions. Please read the script notes to understand what is being changed.
The script EPM_Create_Database_Objects.sql will create the database to store the policy history, the policy schema, the tables, views, functions and stored procedure to support the framework. If installing on an instance that supports Database Compression, then Page Compression will be used in this database.
- Open the SQLCMD script EPM_Create_Database_Objects.sql in SQL Server Management Studio.
- Change the query execution to SQLCMD Mode. In the menu bar select Query -> SQLCMD Mode.
- In the query, configure the variable ServerName with the name of the Central Management Server instance.
- Configure the variable ManagementDatabase with the name of the database where the policy evaluation history will be created. See Figure 3.
| :SETVAR ServerName “WIN2012”:SETVAR ManagementDatabase “MDW”GO:CONNECT $(ServerName)GO |
Figure 3
- Execute the script.
Policy evaluation results will be stored in a SQL Server database designated for database management purposes. Many environments may choose to use a Management Data Warehouse created for Data Collectors, but this is not required. Sizing this database will depend on how many policies are evaluated, how many properties are evaluated in each policy, how many instances are evaluated, and how long the historical data will be maintained.
Update the EPM_EnterpriseEvaluation_4.ps1 PowerShell script variables for the enterprise environment.
- Open EPM_EnterpriseEvaluation_4.ps1 in Notepad or a PowerShell script editor.
- Update the variables identified below with your values. See Figure 4.
$CentralManagementServer: Required.Centralized location of the SQL Server instance where the policy evaluation history database is located. This is the instance and database where the policy evaluation results are written and policies are stored.
$HistoryDatabase: Required. Name of the history database where the policy evaluation results are written.
$ResultDir: Required. File location to write the policy evaluation results during the PowerShell execution. Results are written to this location temporarily.
| # Declare variables to define the central warehouse# in which to write the output, store the policies$CentralManagementServer = “Win2012″$HistoryDatabase = “MDW”# Define the location to write the results of the policy evaluation$ResultDir = “E:\Results\” |
Figure 4
- Save the script in a folder which can be accessed by the scheduling process.
Review the PowerShell script EPM_EnterpriseEvaluation_4.ps1. The scriptrequires three parameters. These parameters will support a granular evaluation strategy.
-ConfigurationGroup: Define the Central Management Server group to evaluate. If an empty string (“”), the PowerShell script will evaluate all servers registered in all of the CMS groups.
-PolicyCategoryFilter: Identifies which category of policies will be evaluated. If an empty string (“”), the PowerShell script will evaluate all polices stored on the Central Management Server.
-EvalMode: Specify the action to take during policy evaluation. Options are Check, Configure. Check will evaluate and report on the evaluation of the policy against the target. Configure will evaluate and report on the evaluation of the policy against the target, and reconfigure any deterministic options that are not in compliance with the policies.
To test the script prior to creating a job, open PowerShell in SQL Server Management Studio.
- Open SQL Server Management Studio. Connect to the Central Management Server.
- In Object Explorer, right-click on the Server and select “Start PowerShell”
- Configure the following commands to your environment. Paste the commands to the SQL Server PowerShell console.
| SL “Insert script folder location”.\EPM_EnterpriseEvaluation_4.ps1 -ConfigurationGroup “Insert Central Management Server Group” -PolicyCategoryFilter “Insert Policy Category” –EvalMode “Check” |
- When the script has completed, run the following statements against the database created in step 3. Results should appear from one or both views.
| SELECT * FROM policy.v_PolicyHistoryGOSELECT * FROM policy.v_EvaluationErrorHistoryGO |
To create the SQL Server Agent job(s):
- Open SQL Server Management Studio. Connect to the Central Management Server. Open SQL Server Agent.
- Right-click the Jobs folder and select “New Job…”.
- Name the job. In the left pane select “Steps”.
- Select the “New…” at the bottom.
- In the New Job Step window name the Job Step. Select PowerShell from the Type drop-down.
- Select the appropriate proxy account in the “Run As” drop-down. This step is required if SQL Server Agent is not running with a domain account that has elevated rights on all instances. See Use a SQL Agent Proxy for Special Tasks for details on configuring a proxy account.
- Enter the following PowerShell script in the command window. Replace the sample parameter values.
| SL “E:\PowerShell Scripts\”.\EPM_EnterpriseEvaluation_4.0.0.ps1 -ConfigurationGroup “Production” -PolicyCategoryFilter “Microsoft Best Practices: Performance” –EvalMode “Check” |
After SL, place the folder location where the EPM_EnterpriseEvaluation_4 is stored from step 4. In the next line, configure the parameters with a Central Management Server Group and a Policy Category. The above is an example which will evaluate all servers in the Production Group and subgroups with the policies in the category “Microsoft Best Practices: Performance”
- Select OK to save the job step. See Figure 5 for an example of the job step.
- In the New Job window, select “Schedule” in the left pane. Configure the schedule to meet the evaluation requirements.
- Select OK to save job.
Figure 5
If you created one job per category, and you want several jobs to execute at once, keep in mind that some job sub systems do not allow more than 2 amount of simultaneous threads, such as the case of PowerShell. As such, you might want to update SQL Agent PowerShell simultaneous threads to a larger number, say 10, using the following example:
| UPDATE msdb.dbo.syssubsystemsSET max_worker_threads = 10WHERE subsystem = N’Powershell’GO |
Note: Running the above command requires a restart of the SQL Agent on SQL Server 2008 and SQL Server 2008R2.
Note2: The above no longer works in SQL Server 2012 or above, whereas the max_worker_thread value will assume its default value of 2 after a SQL Agent restart.
After the PowerShell script was successfully executed and the results of policy evaluation were collected in the management data warehouse, it is very convenient to visualize the data through Reporting Services reports. Steps below describe the process of report configuration and deployment.
Configure the Project properties with SSRS deployment options.
- Double-click ..\ 2Reporting\PolicyReports.sln to open the PolicyReports project in Visual Studio, Business Intelligence Development Studio or SQL Server Data Tools.
- In the right Solution Explorer pane, right-click PolicyDW.rds in the Shared Data Sources folder and select Open.
- Configure the connection string to the Central Management Server instance and database which stores the policy history. Select OK to save.
- Right click on the PolicyReports project and select Properties. See Figure 6. Set the appropriate TargetServerUrl, TargetReportFolder and TargetDataSourceFolder properties of the “PolicyReports” project. These will align with the SQL Server Reporting Services instance.
Figure 6
The visual indicators in the Last Execution Status table and the Failed Policy % By Month chart of the PolicyDashboard report will dynamically change color (see Figure 7) based on thresholds configured in hidden parameters of the report.
Figure 7
- Double-click the PolicyDashboard report in the Reports folder to open.
- In the menu, select View -> Report Data.
- Open the Parameters folder in the left Report Data tab. See Figure 8.
Figure 8
- Right-click PolicyThresholdWarning and select Parameter Properties.
- In the Report Parameter Properties dialog (see Figure 9), select Default Values.
Figure 9
- Change the value to the appropriate value for your environment. The default is 0.5 which will cause the report objects to use a Red color when the failed policy average falls below 50%. Select OK to save.
- Right-click PolicyThresholdCaution and select Parameter Properties.
- In the Report Parameter Properties dialog, select Default Values.
- Change the value to the appropriate value for your environment. The default is 0.17 which will cause the report objects to use an orange color when the failed policy average falls between 17% and 50%. Select OK to save.
When the failed policy average falls between 17% a Yellow color is used. - In the right pane Solution Explorer, right-click on the PolicyReports project and select Deploy.
Appendix A: Additional Considerations
Security
When polices are evaluated through PowerShell, they will execute the policy evaluation in the context of the user issuing the evaluation. This account will require access to all instances and database objects the script will evaluate. The level of permissions will depend on what the policy is evaluating. This extends to the execution account used in a scheduling agent. In SQL Server, the SQL Server Agent job step executes in the context of a specific user. This user may be a proxy account. The account that is specified in the SQL Server Agent step must have access to all objects on all instances that the PowerShell script will be evaluating.
Prior to setting up the SQL Server Agent job, be sure to set up a Proxy Account that has the appropriate rights on the remote instances to evaluate the policies. See Use a SQL Agent Proxy for Special Tasks for details on configuring a proxy account.
Archive
The data stored in the table policy.PolicyHistory is not used to report through the EPM Framework reports. Environments concerned with data space used by the EPM Framework will want to set up a regular process to purge data from this table, unless it is necessary to maintain for compliance.
Below is an example of a cycle that will purge data over 90 days, which can be used inside a SQL Agent job.
| WHILE (SELECT COUNT(PolicyHistoryID) FROM MDW.policy.PolicyHistory WHERE EvaluationDateTime > DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -90)) > 0BEGIN DELETE TOP (5000) FROM MDW.policy.PolicyHistory WHERE EvaluationDateTime > DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -90)END;DELETE FROM MDW.policy.EvaluationErrorHistoryWHERE EvaluationDateTime > DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), -90);GO |
Execution Strategies
Prior to creating the SQL Server Agent job(s), determine the execution strategy for the EPM framework PowerShell script EPM_EnterpriseEvaluation_4.ps1 based on scale, execution time and security. Create SQL Server Agent jobs to execute the policy evaluation according to the strategy.
Administrators managing larger environments may want to implement policy evaluation through multiple parallel jobs that guarantee evaluation completion in the desired scope of time. A large environment that is challenged with a small maintenance window to execute the evaluation may design an execution strategy where the total number of concurrent jobs equals the total number of cores available for the instance.
- EPM_EnterpriseEvaluation_4.ps1 may be configured with multiple SQL Server Agent jobs for each policy category and/or each group of servers.
- EPM_EnterpriseEvaluation_4.ps1 may be configured with a single SQL Server Agent job and multiple steps for each policy category and/or each group of servers.
The script may also be configured to evaluate all policies against all instances (groups) by passing blank strings in as the –ConfigurationGroup and –PolicyCategoryFilter parameters. This configuration is not recommended for environments with a large number of instances and a large number of policies.
The EPM Framework version 4 supports nested server groups defined in the Central Management Server. Note in Figure 10 that the group “Production” has three nested groups. When a parent group is used as the parameter –ConfigurationGroup, all instances registered to the parent group and all instances registered to child groups will be included in the evaluation.
Figure 10
Appendix B: Database Objects
Tables
policy.PolicyHistory: Stores evaluation results from the PowerShell script. The XML results are shred into the table PolicyHistoryDetail. This data is not used for reporting and may be archived and/or purged as deemed necessary.
policy.PolicyHistoryDetail: Stores the shredded results from the EvaluationResults column in policy.PolicyHistory table. This table is the source for all policy result views.
policy.EvaluationErrorHistory: Stores the following types of errors:
- Server connection errors
- Evaluation process cannot write to the PolicyHistory table
- Policy cannot evaluate against an object
Views
policy.v_PolicyHistory : Returns the full historical dataset. Depends on policy.PolicyHistoryDetail.
policy.v_PolicyHistory_Rank: Ranks the policy results for each object on each server by date. Depends on policy.v_PolicyHistory.
policy.v_PolicyHistory_LastEvaluation: Returns the last execution status for each policy evaluation against each object on each server. Depends on policy.v_PolicyHistory_Rank.
policy.v_EvaluationErrorHistory: Returns all evaluation errors from the EvaluationErrorHistory table combined with the PolicyHIstoryDetail table.
policy.v_EvaluationErrorHistory_LastEvaluation: Returns the ranked errors from the v_EvaluationErrorHistory view. The last error for each evaluation is returned when the query includes a filter on EvaluationOrderDesc = 1.
policy.v_ServerGroups: Returns the server groups. Used in reports to drive parameters.
Stored Procedure
policy.epm_Load_PolicyHistoryDetail: Executed during the PowerShell evaluation. Shreds the PolicyHistory XML results and stores in policy.PolicyHistoryDetail and policy.EvaluationErrorHistory.
Function
policy.pfm_ServerGroupInstances: Table-valued function to return the instances registered in a specified Central Management Server group.
Appendix C: Upgrade from previous version
Database Objects
If upgrading from the previous version of EPM, simply execute EPM_Upgrade_Database_Objects.sql to add or change the required objects, without loss of data to your current deployment.
PowerShell Script
Replace EPM_EnterpriseEvaluation_3.0.0.ps1 with EPM_EnterpriseEvaluation_4.ps1, and change the reference in all your jobs accordingly. Refer to step 4 (Configure PowerShell Script) for further information on the script usage.
Reports
Deploy the new reports as detailed in step 7 (Deploy Reports to SQL Server
PBM_Conditions
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Database_Maintenance’, @description=N”, @facet=N’IDatabaseMaintenanceFacet’, @expression=N’ Bool EQ 2 Bool DataAndBackupOnSeparateLogicalVolumes Bool True Bool 0 ‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Database_Performance’, @description=N”, @facet=N’IDatabasePerformanceFacet’, @expression=N’ Bool EQ 2 Bool CollationMatchesModelOrMaster Bool True Bool 0 ‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Database2012′, @description=N”, @facet=N’Database’, @expression=N’ Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool EQ 2 Bool AutoClose Bool False Bool 0
Bool EQ 2 Bool AutoCreateStatisticsEnabled Bool True Bool 0
Bool EQ 2 Bool AutoShrink Bool False Bool 0
Bool EQ 2 Bool AutoUpdateStatisticsAsync Bool False Bool 0
Bool EQ 2 Bool AutoUpdateStatisticsEnabled Bool True Bool 0
Bool EQ 2 Bool CaseSensitive Bool False Bool 0
Bool EQ 2 Bool IsAccessible Bool True Bool 0
Bool EQ 2 Bool IsUpdateable Bool True Bool 0
Bool EQ 2 Numeric PageVerify Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.PageVerify String System.String Checksum
Bool EQ 2 Numeric RecoveryModel Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.RecoveryModel String System.String Simple
Bool GE 2 Numeric SpaceAvailable Numeric System.Double 1024
Bool EQ 2 Numeric UserAccess Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.DatabaseUserAccess String System.String Multiple
Bool 1 Bool OR 2 Bool OR 2 Bool EQ 2 Numeric Status Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.DatabaseStatus String System.String Normal Bool EQ 2 Numeric Status Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.DatabaseStatus String System.String Restoring Bool EQ 2 Numeric Status Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.DatabaseStatus String System.String Standby
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Database2016+’, @description=N”, @facet=N’Database’, @expression=N’ Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool EQ 2 Bool AutoClose Bool False Bool 0
Bool EQ 2 Bool AutoCreateIncrementalStatisticsEnabled Bool False Bool 0
Bool EQ 2 Bool AutoCreateStatisticsEnabled Bool True Bool 0
Bool EQ 2 Bool AutoShrink Bool False Bool 0
Bool EQ 2 Bool AutoUpdateStatisticsAsync Bool False Bool 0
Bool EQ 2 Bool AutoUpdateStatisticsEnabled Bool True Bool 0
Bool EQ 2 Bool CaseSensitive Bool False Bool 0
Bool EQ 2 Bool IsAccessible Bool True Bool 0
Bool EQ 2 Bool IsUpdateable Bool True Bool 0
Bool LE 2 Numeric MaxDop Numeric System.Double 8
Bool EQ 2 Numeric PageVerify Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.PageVerify String System.String Checksum
Bool EQ 2 Numeric RecoveryModel Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.RecoveryModel String System.String Simple
Bool GE 2 Numeric SpaceAvailable Numeric System.Double 1024
Bool EQ 2 Numeric UserAccess Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.DatabaseUserAccess String System.String Multiple
Bool 1 Bool OR 2 Bool OR 2 Bool EQ 2 Numeric Status Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.DatabaseStatus String System.String Normal Bool EQ 2 Numeric Status Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.DatabaseStatus String System.String Restoring Bool EQ 2 Numeric Status Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.DatabaseStatus String System.String Standby
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’DataFile2008′, @description=N”, @facet=N’DataFile’, @expression=N’ Bool AND 2 Bool AND 2 Bool GE 2 Numeric AvailableSpace Numeric System.Double 5120
Bool EQ 2 Numeric GrowthType Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.FileGrowthType String System.String KB
Bool EQ 2 Bool IsOffline Bool False Bool 0
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’DataFile2012+’, @description=N”, @facet=N’DataFile’, @expression=N’ Bool AND 2 Bool AND 2 Bool AND 2 Bool GE 2 Numeric AvailableSpace Numeric System.Double 5120
Bool EQ 2 Numeric GrowthType Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.FileGrowthType String System.String KB
Bool EQ 2 Bool IsOffline Bool False Bool 0
Bool GE 2 Numeric VolumeFreeSpace Numeric System.Double 10240
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Endpoint’, @description=N”, @facet=N’Endpoint’, @expression=N’ Bool EQ 2 Numeric EndpointState Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.EndpointState String System.String Started ‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’LogFile2008′, @description=N”, @facet=N’LogFile’, @expression=N’ Bool AND 2 Bool EQ 2 Numeric GrowthType Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.FileGrowthType String System.String KB
Bool EQ 2 Bool IsOffline Bool False Bool 0
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’LogFile2012+’, @description=N”, @facet=N’LogFile’, @expression=N’ Bool AND 2 Bool AND 2 Bool EQ 2 Numeric GrowthType Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.FileGrowthType String System.String KB
Bool EQ 2 Bool IsOffline Bool False Bool 0
Bool GE 2 Numeric VolumeFreeSpace Numeric System.Double 5120
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Login-Type’, @description=N”, @facet=N’Login’, @expression=N’ Bool OR 2 Bool OR 2 Bool EQ 2 Numeric LoginType Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.LoginType String System.String SqlLogin
Bool EQ 2 Numeric LoginType Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.LoginType String System.String WindowsUser
Bool EQ 2 Numeric LoginType Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.LoginType String System.String WindowsGroup
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’OS2008′, @description=N”, @facet=N’Server’, @expression=N’ Bool AND 2 Bool AND 2 Bool EQ 2 String OSVersion String System.String 6.1 (7601)
Bool GT 2 Numeric PhysicalMemory Numeric System.Double 8000
Bool GT 2 Numeric Processors Numeric System.Double 1
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’OS2012+’, @description=N”, @facet=N’Server’, @expression=N’ Bool AND 2 Bool AND 2 Bool AND 2 Bool EQ 2 String OSVersion String System.String 6.3 (14393)
Bool GT 2 Numeric PhysicalMemory Numeric System.Double 8000
Bool GT 2 Numeric PhysicalMemoryUsageInKB Numeric System.Double 2000000
Bool GT 2 Numeric Processors Numeric System.Double 1
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server Configuration’, @description=N”, @facet=N’IServerConfigurationFacet’, @expression=N’ Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool EQ 2 Bool AllowUpdates Bool False Bool 0
Bool EQ 2 Bool DefaultBackupCompressionEnabled Bool True Bool 0
Bool EQ 2 Numeric NetworkPacketSize Numeric System.Double 4096
Bool EQ 2 Numeric UserConnections Numeric System.Double 0
Bool 1 Bool OR 2 Bool GE 2 Numeric FillFactor Numeric System.Double 90 Bool EQ 2 Numeric FillFactor Numeric System.Double 0
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server Installation 2008′, @description=N”, @facet=N’IServerSetupFacet’, @expression=N’ Bool AND 2 Bool AND 2 Bool EQ 2 Numeric LoginMode Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.ServerLoginMode String System.String Mixed
Bool LIKE 2 String TempdbLogPath String System.String H%MSSQL10%MSSQL%Data%
Bool LIKE 2 String TempdbPrimaryFilePath String System.String H%MSSQL10%MSSQL%Data%
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server Installation 2012′, @description=N”, @facet=N’IServerSetupFacet’, @expression=N’ Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool LIKE 2 String DefaultFile String System.String E%MSSQL11%MSSQL%DATA%
Bool LIKE 2 String DefaultLog String System.String F%MSSQL11%MSSQL%DATA%
Bool EQ 2 Numeric LoginMode Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.ServerLoginMode String System.String Mixed
Bool LIKE 2 String TempdbLogPath String System.String H%MSSQL11%MSSQL%DATA%
Bool LIKE 2 String TempdbPrimaryFilePath String System.String H%MSSQL11%MSSQL%DATA%
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server Installation 2016′, @description=N”, @facet=N’IServerSetupFacet’, @expression=N’ Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool LIKE 2 String DefaultFile String System.String E%MSSQL13%MSSQL%DATA%
Bool LIKE 2 String DefaultLog String System.String F%MSSQL13%MSSQL%DATA%
Bool EQ 2 Numeric LoginMode Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.ServerLoginMode String System.String Mixed
Bool LIKE 2 String TempdbLogPath String System.String H%MSSQL13%MSSQL%DATA%
Bool LIKE 2 String TempdbPrimaryFilePath String System.String H%MSSQL13%MSSQL%DATA%
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server Version 2008′, @description=N”, @facet=N’Server’, @expression=N’ Bool LE 2 Numeric VersionMajor Numeric System.Double 10 ‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server Version 2012′, @description=N”, @facet=N’Server’, @expression=N’ Bool EQ 2 Numeric VersionMajor Numeric System.Double 11 ‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server Version 2012+’, @description=N”, @facet=N’Server’, @expression=N’ Bool GE 2 Numeric VersionMajor Numeric System.Double 11 ‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server Version 2016′, @description=N”, @facet=N’Server’, @expression=N’ Bool EQ 2 Numeric VersionMajor Numeric System.Double 13 ‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server Version 2016+’, @description=N”, @facet=N’Server’, @expression=N’ Bool GE 2 Numeric VersionMajor Numeric System.Double 13 ‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server2008′, @description=N”, @facet=N’Server’, @expression=N’ Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool LIKE 2 String BackupDirectory String System.String G%Sqlbackup%Database%
Bool LIKE 2 String ErrorLogPath String System.String D%MSSQL10%MSSQL%Log%
Bool LIKE 2 String RootDirectory String System.String C:\Program Files\Microsoft SQL Server\MSSQL10%MSSQL%
Bool EQ 2 Bool IsCaseSensitive Bool False Bool 0
Bool EQ 2 Bool IsSingleUser Bool False Bool 0
Bool EQ 2 String Language String System.String English (United States)
Bool LIKE 2 String MasterDBLogPath String System.String D%MSSQL10%MSSQL%DATA%
Bool LIKE 2 String MasterDBPath String System.String D%MSSQL10%MSSQL%DATA%
Bool EQ 2 Numeric ServiceStartMode Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.ServiceStartMode String System.String Auto
Bool EQ 2 Numeric Status Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.ServerStatus String System.String Online
Bool EQ 2 Bool TcpEnabled Bool True Bool 0
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server2012′, @description=N”, @facet=N’Server’, @expression=N’ Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool LIKE 2 String BackupDirectory String System.String G%Sqlbackup%Database%
Bool LIKE 2 String DefaultFile String System.String E%MSSQL11%%MSSQL%DATA%
Bool LIKE 2 String DefaultLog String System.String F%MSSQL11%%MSSQL%DATA%
Bool LIKE 2 String ErrorLogPath String System.String D%MSSQL11%MSSQL%Log%
Bool LIKE 2 String RootDirectory String System.String C:\Program Files\Microsoft SQL Server\MSSQL11%MSSQL%
Bool EQ 2 Bool IsCaseSensitive Bool False Bool 0
Bool EQ 2 Bool IsSingleUser Bool False Bool 0
Bool EQ 2 String Language String System.String English (United States)
Bool LIKE 2 String MasterDBLogPath String System.String D%MSSQL11%MSSQL%DATA%
Bool LIKE 2 String MasterDBPath String System.String D%MSSQL11%MSSQL%DATA%
Bool EQ 2 Numeric ServiceStartMode Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.ServiceStartMode String System.String Auto
Bool EQ 2 Numeric Status Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.ServerStatus String System.String Online
Bool EQ 2 Bool TcpEnabled Bool True Bool 0
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’Server2016′, @description=N”, @facet=N’Server’, @expression=N’ Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool AND 2 Bool LIKE 2 String BackupDirectory String System.String G%Sqlbackup%Database%
Bool LIKE 2 String DefaultFile String System.String E%MSSQL13%MSSQL%DATA%
Bool LIKE 2 String DefaultLog String System.String F%MSSQL13%MSSQL%DATA%
Bool LIKE 2 String ErrorLogPath String System.String D%MSSQL13%MSSQL%Log%
Bool LIKE 2 String RootDirectory String System.String C:\Program Files\Microsoft SQL Server\MSSQL13%MSSQL%
Bool EQ 2 Bool IsCaseSensitive Bool False Bool 0
Bool EQ 2 Bool IsSingleUser Bool False Bool 0
Bool EQ 2 String Language String System.String English (United States)
Bool LIKE 2 String MasterDBLogPath String System.String D%MSSQL13%MSSQL%DATA%
Bool LIKE 2 String MasterDBPath String System.String D%MSSQL13%MSSQL%DATA%
Bool EQ 2 Numeric ServiceStartMode Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.ServiceStartMode String System.String Auto
Bool EQ 2 Numeric Status Numeric Enum Numeric 2 String System.String Microsoft.SqlServer.Management.Smo.ServerStatus String System.String Online
Bool EQ 2 Bool TcpEnabled Bool True Bool 0
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
Declare @condition_id int
EXEC msdb.dbo.sp_syspolicy_add_condition @name=N’SurfaceAreaConfiguration’, @description=N”, @facet=N’ISurfaceAreaFacet’, @expression=N’ Bool AND 2 Bool EQ 2 Bool RemoteDacEnabled Bool True Bool 0
Bool EQ 2 Bool XPCmdShellEnabled Bool False Bool 0
‘, @is_name_condition=0, @obj_name=N”, @condition_id=@condition_id OUTPUT
Select @condition_id
GO
PBM Create Categories
use msdb
go
EXEC [dbo].[sp_syspolicy_add_policy_category] ‘dbDooT-2008’, 1, 13
go
EXEC [dbo].[sp_syspolicy_add_policy_category] ‘dbDooT-2012’, 1, 14
go
EXEC [dbo].[sp_syspolicy_add_policy_category] ‘dbDooT-2016’, 1, 15
go
EXEC [dbo].[sp_syspolicy_add_policy_category] ‘dbDooT-2019’, 1, 16
go
EXEC [dbo].[sp_syspolicy_add_policy_category] ‘dbDooT-2008_db’, 1, 17
go
EXEC [dbo].[sp_syspolicy_add_policy_category] ‘dbDooT-2012_db’, 1, 18
go
EXEC [dbo].[sp_syspolicy_add_policy_category] ‘dbDooT-2016_db’, 1, 19
go
EXEC [dbo].[sp_syspolicy_add_policy_category] ‘dbDooT-2019_db’, 1, 20
go
PBM_Policies
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Database_2012_ObjectSet’, @facet=N’Database’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Database_2012_ObjectSet’, @type_skeleton=N’Server/Database’, @type=N’DATABASE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Database_2012′, @condition_name=N’Database2012′, @policy_category=N’dbDooT-2012_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’Database_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Database_2016_ObjectSet’, @facet=N’Database’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Database_2016_ObjectSet’, @type_skeleton=N’Server/Database’, @type=N’DATABASE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Database_2016′, @condition_name=N’Database2016+’, @policy_category=N’dbDooT-2016_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Database_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Database_2019_ObjectSet’, @facet=N’Database’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Database_2019_ObjectSet’, @type_skeleton=N’Server/Database’, @type=N’DATABASE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Database_2019′, @condition_name=N’Database2016+’, @policy_category=N’dbDooT-2019_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Database_2019_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Database_Maintenance_2012_ObjectSet’, @facet=N’IDatabaseMaintenanceFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Database_Maintenance_2012_ObjectSet’, @type_skeleton=N’Server/Database’, @type=N’DATABASE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Database_Maintenance_2012′, @condition_name=N’Database_Maintenance’, @policy_category=N’dbDooT-2012_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’Database_Maintenance_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Database_Maintenance_2016_ObjectSet’, @facet=N’IDatabaseMaintenanceFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Database_Maintenance_2016_ObjectSet’, @type_skeleton=N’Server/Database’, @type=N’DATABASE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Database_Maintenance_2016′, @condition_name=N’Database_Maintenance’, @policy_category=N’dbDooT-2016_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Database_Maintenance_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Database_Maintenance_2019_ObjectSet’, @facet=N’IDatabaseMaintenanceFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Database_Maintenance_2019_ObjectSet’, @type_skeleton=N’Server/Database’, @type=N’DATABASE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Database_Maintenance_2019′, @condition_name=N’Database_Maintenance’, @policy_category=N’dbDooT-2019_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Database_Maintenance_2019_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Database_Performance_2012_ObjectSet’, @facet=N’IDatabasePerformanceFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Database_Performance_2012_ObjectSet’, @type_skeleton=N’Server/Database’, @type=N’DATABASE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Database_Performance_2012′, @condition_name=N’Database_Performance’, @policy_category=N’dbDooT-2012_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’Database_Performance_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Database_Performance_2016_ObjectSet’, @facet=N’IDatabasePerformanceFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Database_Performance_2016_ObjectSet’, @type_skeleton=N’Server/Database’, @type=N’DATABASE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Database_Performance_2016′, @condition_name=N’Database_Performance’, @policy_category=N’dbDooT-2016_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Database_Performance_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Database_Performance_2019_ObjectSet’, @facet=N’IDatabasePerformanceFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Database_Performance_2019_ObjectSet’, @type_skeleton=N’Server/Database’, @type=N’DATABASE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Database_Performance_2019′, @condition_name=N’Database_Performance’, @policy_category=N’dbDooT-2019_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Database_Performance_2019_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’DataFile_2008_ObjectSet’, @facet=N’DataFile’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’DataFile_2008_ObjectSet’, @type_skeleton=N’Server/Database/FileGroup/File’, @type=N’FILE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/FileGroup/File’, @level_name=N’File’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/FileGroup’, @level_name=N’FileGroup’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’DataFile_2008′, @condition_name=N’DataFile2008′, @policy_category=N’dbDooT-2008_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2008′, @object_set=N’DataFile_2008_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’DataFile_2012_ObjectSet’, @facet=N’DataFile’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’DataFile_2012_ObjectSet’, @type_skeleton=N’Server/Database/FileGroup/File’, @type=N’FILE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/FileGroup/File’, @level_name=N’File’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/FileGroup’, @level_name=N’FileGroup’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’DataFile_2012′, @condition_name=N’DataFile2012+’, @policy_category=N’dbDooT-2012_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’DataFile_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’DataFile_2016_ObjectSet’, @facet=N’DataFile’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’DataFile_2016_ObjectSet’, @type_skeleton=N’Server/Database/FileGroup/File’, @type=N’FILE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/FileGroup/File’, @level_name=N’File’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/FileGroup’, @level_name=N’FileGroup’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’DataFile_2016′, @condition_name=N’DataFile2012+’, @policy_category=N’dbDooT-2016_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’DataFile_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’DataFile_2019_ObjectSet’, @facet=N’DataFile’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’DataFile_2019_ObjectSet’, @type_skeleton=N’Server/Database/FileGroup/File’, @type=N’FILE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/FileGroup/File’, @level_name=N’File’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/FileGroup’, @level_name=N’FileGroup’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’DataFile_2019′, @condition_name=N’DataFile2012+’, @policy_category=N’dbDooT-2019_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’DataFile_2019_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Endpoint_2012_ObjectSet’, @facet=N’Endpoint’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Endpoint_2012_ObjectSet’, @type_skeleton=N’Server/Endpoint’, @type=N’ENDPOINT’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Endpoint’, @level_name=N’Endpoint’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Endpoint_2012′, @condition_name=N’Endpoint’, @policy_category=N’dbDooT-2012′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’Endpoint_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Endpoint_2016_ObjectSet’, @facet=N’Endpoint’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Endpoint_2016_ObjectSet’, @type_skeleton=N’Server/Endpoint’, @type=N’ENDPOINT’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Endpoint’, @level_name=N’Endpoint’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Endpoint_2016′, @condition_name=N’Endpoint’, @policy_category=N’dbDooT-2016′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Endpoint_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Endpoint_2019_ObjectSet’, @facet=N’Endpoint’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Endpoint_2019_ObjectSet’, @type_skeleton=N’Server/Endpoint’, @type=N’ENDPOINT’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Endpoint’, @level_name=N’Endpoint’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Endpoint_2019′, @condition_name=N’Endpoint’, @policy_category=N’dbDooT-2019′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Endpoint_2019_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’LogFile_2008_ObjectSet’, @facet=N’LogFile’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’LogFile_2008_ObjectSet’, @type_skeleton=N’Server/Database/LogFile’, @type=N’LOGFILE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/LogFile’, @level_name=N’LogFile’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’LogFile_2008′, @condition_name=N’LogFile2008′, @policy_category=N’dbDooT-2008_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2008′, @object_set=N’LogFile_2008_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’LogFile_2012_ObjectSet’, @facet=N’LogFile’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’LogFile_2012_ObjectSet’, @type_skeleton=N’Server/Database/LogFile’, @type=N’LOGFILE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/LogFile’, @level_name=N’LogFile’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’LogFile_2012′, @condition_name=N’LogFile2012+’, @policy_category=N’dbDooT-2012_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’LogFile_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’LogFile_2016_ObjectSet’, @facet=N’LogFile’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’LogFile_2016_ObjectSet’, @type_skeleton=N’Server/Database/LogFile’, @type=N’LOGFILE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/LogFile’, @level_name=N’LogFile’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’LogFile_2016′, @condition_name=N’LogFile2012+’, @policy_category=N’dbDooT-2016_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’LogFile_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’LogFile_2019_ObjectSet’, @facet=N’LogFile’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’LogFile_2019_ObjectSet’, @type_skeleton=N’Server/Database/LogFile’, @type=N’LOGFILE’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database/LogFile’, @level_name=N’LogFile’, @condition_name=N”, @target_set_level_id=0
EXEC msdb.dbo.sp_syspolicy_add_target_set_level @target_set_id=@target_set_id, @type_skeleton=N’Server/Database’, @level_name=N’Database’, @condition_name=N”, @target_set_level_id=0
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’LogFile_2019′, @condition_name=N’LogFile2012+’, @policy_category=N’dbDooT-2019_db’, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’LogFile_2019_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’OS_2008_ObjectSet’, @facet=N’Server’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’OS_2008_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’OS_2008′, @condition_name=N’OS2008′, @policy_category=N’dbDooT-2008′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2008′, @object_set=N’OS_2008_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’OS_2012_ObjectSet’, @facet=N’Server’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’OS_2012_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’OS_2012′, @condition_name=N’OS2012+’, @policy_category=N’dbDooT-2012′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’OS_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’OS_2016_ObjectSet’, @facet=N’Server’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’OS_2016_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’OS_2016′, @condition_name=N’OS2012+’, @policy_category=N’dbDooT-2016′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’OS_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’OS_2019_ObjectSet’, @facet=N’Server’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’OS_2019_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’OS_2019′, @condition_name=N’OS2012+’, @policy_category=N’dbDooT-2019′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’OS_2019_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_2008_ObjectSet’, @facet=N’Server’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_2008_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_2008′, @condition_name=N’Server2008′, @policy_category=N’dbDooT-2008′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2008′, @object_set=N’Server_2008_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_2012_ObjectSet’, @facet=N’Server’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_2012_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_2012′, @condition_name=N’Server2012′, @policy_category=N’dbDooT-2012′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’Server_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_2016_ObjectSet’, @facet=N’Server’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_2016_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_2016′, @condition_name=N’Server2016′, @policy_category=N’dbDooT-2016′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Server_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_2019_ObjectSet’, @facet=N’Server’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_2019_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_2019′, @condition_name=N’Server2016′, @policy_category=N’dbDooT-2019′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Server_2019_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_Configuration_2008_ObjectSet’, @facet=N’IServerConfigurationFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_Configuration_2008_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_Configuration_2008′, @condition_name=N’Server Configuration’, @policy_category=N’dbDooT-2008′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2008′, @object_set=N’Server_Configuration_2008_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_Configuration_2012_ObjectSet’, @facet=N’IServerConfigurationFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_Configuration_2012_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_Configuration_2012′, @condition_name=N’Server Configuration’, @policy_category=N’dbDooT-2012′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’Server_Configuration_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_Configuration_2016_ObjectSet’, @facet=N’IServerConfigurationFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_Configuration_2016_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_Configuration_2016′, @condition_name=N’Server Configuration’, @policy_category=N’dbDooT-2016′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Server_Configuration_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_Configuration_2019_ObjectSet’, @facet=N’IServerConfigurationFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_Configuration_2019_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_Configuration_2019′, @condition_name=N’Server Configuration’, @policy_category=N’dbDooT-2019′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Server_Configuration_2019_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_Installation_2008_ObjectSet’, @facet=N’IServerSetupFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_Installation_2008_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_Installation_2008′, @condition_name=N’Server Installation 2008′, @policy_category=N’dbDooT-2008′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2008′, @object_set=N’Server_Installation_2008_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_Installation_2012_ObjectSet’, @facet=N’IServerSetupFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_Installation_2012_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_Installation_2012′, @condition_name=N’Server Installation 2012′, @policy_category=N’dbDooT-2012′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’Server_Installation_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_Installation_2016_ObjectSet’, @facet=N’IServerSetupFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_Installation_2016_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_Installation_2016′, @condition_name=N’Server Installation 2016′, @policy_category=N’dbDooT-2016′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Server_Installation_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’Server_Installation_2019_ObjectSet’, @facet=N’IServerSetupFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’Server_Installation_2019_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’Server_Installation_2019′, @condition_name=N’Server Installation 2016′, @policy_category=N’dbDooT-2019′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’Server_Installation_2019_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’SurfaceAreaConfiguration_2008_ObjectSet’, @facet=N’ISurfaceAreaFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’SurfaceAreaConfiguration_2008_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’SurfaceAreaConfiguration_2008′, @condition_name=N’SurfaceAreaConfiguration’, @policy_category=N’dbDooT-2008′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2008′, @object_set=N’SurfaceAreaConfiguration_2008_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’SurfaceAreaConfiguration_2012_ObjectSet’, @facet=N’ISurfaceAreaFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’SurfaceAreaConfiguration_2012_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’SurfaceAreaConfiguration_2012′, @condition_name=N’SurfaceAreaConfiguration’, @policy_category=N’dbDooT-2012′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2012′, @object_set=N’SurfaceAreaConfiguration_2012_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’SurfaceAreaConfiguration_2016_ObjectSet’, @facet=N’ISurfaceAreaFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’SurfaceAreaConfiguration_2016_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’SurfaceAreaConfiguration_2016′, @condition_name=N’SurfaceAreaConfiguration’, @policy_category=N’dbDooT-2016′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’SurfaceAreaConfiguration_2016_ObjectSet’
Select @policy_id
GO
Declare @object_set_id int
EXEC msdb.dbo.sp_syspolicy_add_object_set @object_set_name=N’SurfaceAreaConfiguration_2019_ObjectSet’, @facet=N’ISurfaceAreaFacet’, @object_set_id=@object_set_id OUTPUT
Select @object_set_id
Declare @target_set_id int
EXEC msdb.dbo.sp_syspolicy_add_target_set @object_set_name=N’SurfaceAreaConfiguration_2019_ObjectSet’, @type_skeleton=N’Server’, @type=N’SERVER’, @enabled=True, @target_set_id=@target_set_id OUTPUT
Select @target_set_id
GO
Declare @policy_id int
EXEC msdb.dbo.sp_syspolicy_add_policy @name=N’SurfaceAreaConfiguration_2019′, @condition_name=N’SurfaceAreaConfiguration’, @policy_category=N’dbDooT-2019′, @description=N”, @help_text=N”, @help_link=N”, @schedule_uid=N’00000000-0000-0000-0000-000000000000′, @execution_mode=0, @is_enabled=False, @policy_id=@policy_id OUTPUT, @root_condition_name=N’Server Version 2016+’, @object_set=N’SurfaceAreaConfiguration_2019_ObjectSet’
Select @policy_id
GO
Create_CMS_Login
USE [master]
GO
/ Object: Login [DBG\svc_dbDooT-SQL] Script Date: 27/05/2021 14:58:45 /
CREATE LOGIN [DBG\svc_dbDooT-SQL] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
GO
USE [dbDooT]
GO
/ Object: User [DBG\svc_dbDooT-SQL] Script Date: 27/05/2021 14:59:05 /
CREATE USER [DBG\svc_dbDooT-SQL] FOR LOGIN [DBG\svc_dbDooT-SQL] WITH DEFAULT_SCHEMA=[dbo]
GO
ALTER ROLE [db_owner] ADD MEMBER [DBG\svc_dbDooT-SQL]
GO
USE [msdb]
GO
/ Object: User [DBG\svc_dbDooT-SQL] Script Date: 27/05/2021 14:59:36 /
CREATE USER [DBG\svc_dbDooT-SQL] FOR LOGIN [DBG\svc_dbDooT-SQL] WITH DEFAULT_SCHEMA=[dbo]
GO
ALTER ROLE [db_datareader] ADD MEMBER [DBG\svc_dbDooT-SQL]
GO
ALTER ROLE [PolicyAdministratorRole] ADD MEMBER [DBG\svc_dbDooT-SQL]
GO
Create_Job_PBM-dbDooT
USE [msdb]
GO
/ Object: Job [PBM-dbDooT] Script Date: 24/06/2021 12:36:17 / BEGIN TRANSACTION DECLARE @ReturnCode INT SELECT @ReturnCode = 0 / Object: JobCategory [[Uncategorized (Local)]] Script Date: 24/06/2021 12:36:17 /
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]’ AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N’JOB’, @type=N’LOCAL’, @name=N'[Uncategorized (Local)]’
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
END
DECLARE @jobId BINARY(16)
EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N’PBM-dbDooT’,
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=0,
@description=N’Job that runs the EPM Policy evaluations scipt aginst the defined Central Management Server group. There are 3 steps which are currently commented out. These stesp are for the database checks which will be introduced in Phase 2. In Phase1 we are only doing SQL Server instance and some OS checks.’,
@category_name=N'[Uncategorized (Local)]’,
@owner_login_name=N’sa’, @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/ Object: Step [Run EPM Powershell Script 2008] Script Date: 24/06/2021 12:36:17 / EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Run EPM Powershell Script 2008′, @step_id=1, @cmdexec_success_code=0, @on_success_action=3, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N’PowerShell’, @command=N’SL “D:\Shared\EPM” .\EPM_EnterpriseEvaluation_4.ps1 -ConfigurationGroup “2008” -PolicyCategoryFilter “dbDooT-2008” –EvalMode “Check”‘, @database_name=N’master’, @flags=0, @proxy_name=N’EPM-PBM’ IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback / Object: Step [Run EPM Powershell Script 2012] Script Date: 24/06/2021 12:36:18 / EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Run EPM Powershell Script 2012′, @step_id=2, @cmdexec_success_code=0, @on_success_action=3, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N’PowerShell’, @command=N’SL “D:\Shared\EPM” .\EPM_EnterpriseEvaluation_4.ps1 -ConfigurationGroup “2012” -PolicyCategoryFilter “dbDooT-2012” –EvalMode “Check”‘, @database_name=N’master’, @flags=0, @proxy_name=N’EPM-PBM’ IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback / Object: Step [Run EPM Powershell Script 2016] Script Date: 24/06/2021 12:36:18 / EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Run EPM Powershell Script 2016′, @step_id=3, @cmdexec_success_code=0, @on_success_action=3, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N’PowerShell’, @command=N’SL “D:\Shared\EPM” .\EPM_EnterpriseEvaluation_4.ps1 -ConfigurationGroup “2016” -PolicyCategoryFilter “dbDooT-2016” –EvalMode “Check”‘, @database_name=N’master’, @flags=0, @proxy_name=N’EPM-PBM’ IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback / Object: Step [Run EPM Powershell Script 2019] Script Date: 24/06/2021 12:36:18 / EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Run EPM Powershell Script 2019′, @step_id=4, @cmdexec_success_code=0, @on_success_action=3, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N’PowerShell’, @command=N’SL “D:\Shared\EPM” .\EPM_EnterpriseEvaluation_4.ps1 -ConfigurationGroup “2019” -PolicyCategoryFilter “dbDooT-2019” –EvalMode “Check”‘, @database_name=N’master’, @flags=0, @proxy_name=N’EPM-PBM’ IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback / Object: Step [Run EPM Powershell Script 2008_db – Phase2] Script Date: 24/06/2021 12:36:18 / EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Run EPM Powershell Script 2008_db – Phase2′, @step_id=5, @cmdexec_success_code=0, @on_success_action=3, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N’PowerShell’, @command=N’SL “D:\Shared\EPM” .\EPM_EnterpriseEvaluation_4.ps1 -ConfigurationGroup “2008” -PolicyCategoryFilter “dbDooT-2008_db” –EvalMode “Check”‘, @database_name=N’master’, @flags=0, @proxy_name=N’EPM-PBM’ IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback / Object: Step [Run EPM Powershell Script 2012_db – Phase2] Script Date: 24/06/2021 12:36:18 / EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Run EPM Powershell Script 2012_db – Phase2′, @step_id=6, @cmdexec_success_code=0, @on_success_action=3, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N’PowerShell’, @command=N’SL “D:\Shared\EPM” .\EPM_EnterpriseEvaluation_4.ps1 -ConfigurationGroup “2012” -PolicyCategoryFilter “dbDooT-2012_db” –EvalMode “Check”‘, @database_name=N’master’, @flags=0, @proxy_name=N’EPM-PBM’ IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback / Object: Step [Run EPM Powershell Script 2016_db – Phase2] Script Date: 24/06/2021 12:36:18 / EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Run EPM Powershell Script 2016_db – Phase2′, @step_id=7, @cmdexec_success_code=0, @on_success_action=3, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N’PowerShell’, @command=N’SL “D:\Shared\EPM” .\EPM_EnterpriseEvaluation_4.ps1 -ConfigurationGroup “2016” -PolicyCategoryFilter “dbDooT-2016_db” –EvalMode “Check”‘, @database_name=N’master’, @flags=0, @proxy_name=N’EPM-PBM’ IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback / Object: Step [Run EPM Powershell Script 2019_db – Phase2] Script Date: 24/06/2021 12:36:18 / EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Run EPM Powershell Script 2019_db – Phase2′, @step_id=8, @cmdexec_success_code=0, @on_success_action=3, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N’PowerShell’, @command=N’SL “D:\Shared\EPM” .\EPM_EnterpriseEvaluation_4.ps1 -ConfigurationGroup “2019” -PolicyCategoryFilter “dbDooT-2019_db” –EvalMode “Check”‘, @database_name=N’master’, @flags=0, @proxy_name=N’EPM-PBM’ IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback / Object: Step [Extract Condition Results] Script Date: 24/06/2021 12:36:18 / EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Extract Condition Results’, @step_id=9, @cmdexec_success_code=0, @on_success_action=3, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N’TSQL’, @command=N’EXEC [ExtractConditionResults] go’, @database_name=N’dbDooT’, @flags=0 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback / Object: Step [Remove Old Data] Script Date: 24/06/2021 12:36:18 /
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Remove Old Data’,
@step_id=10,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N’TSQL’,
@command=N’SET QUOTED_IDENTIFIER ON
go
USE [dbDooT]
GO
declare @onemonthback varchar(50)
set @onemonthback = dateadd (mm, -1, getdate())
declare @oneweekback varchar(50)
set @oneweekback = dateadd (dd, -7, getdate())
delete from [dbDooT].[policy].[EvaluationErrorHistory]
where [EvaluationDateTime] <= @onemonthback
delete from [dbDooT].[policy].[PolicyHistory]
where [EvaluationDateTime] <= @onemonthback
delete from [dbDooT].[policy].[PolicyConditionResults]
where [EvaluationDateTime] <= @oneweekback
GO’,
@database_name=N’dbDooT’,
@flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N’PBM-dbDooT-Daily’,
@enabled=1,
@freq_type=4,
@freq_interval=1,
@freq_subday_type=1,
@freq_subday_interval=0,
@freq_relative_interval=0,
@freq_recurrence_factor=0,
@active_start_date=20210215,
@active_end_date=99991231,
@active_start_time=70000,
@active_end_time=235959,
@schedule_uid=N’46e71a88-b1b1-4bbc-be81-0637cab2435e’
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)’
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:
GO
Create_Proxy
USE [msdb]
GO
/*First need to create a credential, this needs to eb a domain accoutn which has access to all SQl Servers with the following permissions, the msdb role “PolicyAdministratorRole” assigned to it */
/ Object: ProxyAccount [EPM-PBM] Script Date: 12/02/2021 14:59:45 /
EXEC msdb.dbo.sp_add_proxy @proxy_name=N’EPM-PBM’,@credential_name=N’EPM-PBM’,
@enabled=1
GO
EXEC msdb.dbo.sp_grant_proxy_to_subsystem @proxy_name=N’EPM-PBM’, @subsystem_id=12
GO
Create_Table_PolicyConditionResults
USE [dbDooT]
GO
/ Object: Table [policy].[PolicyConditionResults] Script Date: 07/05/2021 14:27:23 /
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [policy].[PolicyConditionResults](
[PolicyConditionResultsID] [int] IDENTITY(1,1) NOT NULL,
[EvaluationDateTime] [datetime] NULL,
[EvaluatedPolicy] nvarchar NULL,
[EvaluatedServer] nvarchar NULL,
[EvaluatedObject] nvarchar NULL,
[EvaluatedCondition] nvarchar NULL,
[EvaluatedConditionResult] nvarchar NULL,
[PolicyHistoryID] [int] NULL,
[CategoryName] nvarchar NULL,
CONSTRAINT [PK_PolicyConditionResults] PRIMARY KEY CLUSTERED
(
[PolicyConditionResultsID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
–The following index ensures ref integrity and avoids duplicate entires.
CREATE UNIQUE NONCLUSTERED INDEX [IDX_Unique] ON [policy].[PolicyConditionResults]
(
[EvaluationDateTime] ASC,
[EvaluatedPolicy] ASC,
[EvaluatedServer] ASC,
[EvaluatedObject] ASC,
[EvaluatedCondition] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = ON, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
Create_Target_Login
USE [master]
GO
/ Object: Login [DBG\olaftor-a] Script Date: 21/04/2021 15:00:28 /
CREATE LOGIN [DBG\dbDooT-MSSQL] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
GO
USE [msdb]
GO
ALTER ROLE [PolicyAdministratorRole] ADD MEMBER [DBG\dbDooT-MSSQL]
GO
EPM_Create_Database_Objects
/*
SQLCMD script to generate the required objects to support a centralized Policy-Based Management solution.
This is the first script to run.
Set the variables to define the server and database which stores the policy results.
*/
:SETVAR ServerName “SYBENG01”
:SETVAR ManagementDatabase “dbDooT”
GO
:CONNECT $(ServerName)
GO
–Create the specified database if it does not exist
IF NOT EXISTS(SELECT * FROM sys.databases WHERE name = ‘$(ManagementDatabase)’)
CREATE DATABASE $(ManagementDatabase)
GO
–Create a schema to support the EPM framework objects.
USE $(ManagementDatabase)
GO
IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N’policy’)
EXEC sys.sp_executesql N’CREATE SCHEMA [policy] AUTHORIZATION [dbo]’
–Start create tables and indexes
–Create the table to store the results from the PowerShell evaluation.
IF NOT EXISTS(SELECT * FROM sys.objects WHERE type = N’U’ AND name = N’PolicyHistory’)
BEGIN
CREATE TABLE [policy].[PolicyHistory](
[PolicyHistoryID] [int] IDENTITY NOT NULL ,
[EvaluatedServer] nvarchar NULL,
[EvaluationDateTime] [datetime] NULL,
[EvaluatedPolicy] nvarchar NULL,
[EvaluationResults] [xml] NOT NULL,
CONSTRAINT PK_PolicyHistory PRIMARY KEY CLUSTERED (PolicyHistoryID)
)
ALTER TABLE [policy].[PolicyHistory] ADD CONSTRAINT [DF_PolicyHistory_EvaluationDateTime] DEFAULT (GETDATE()) FOR [EvaluationDateTime]
END
GO
IF EXISTS(SELECT * FROM sys.columns WHERE object_id = object_id(‘policy.policyhistory’) AND name = ‘PolicyResult’)
BEGIN
ALTER TABLE policy.PolicyHistory
DROP COLUMN PolicyResult
END
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistory]’) AND name = N’IX_EvaluationResults’)
DROP INDEX IX_EvaluationResults ON policy.PolicyHistory
GO
CREATE PRIMARY XML INDEX IX_EvaluationResults ON policy.PolicyHistory (EvaluationResults)
GO
CREATE XML INDEX IX_EvaluationResults_PROPERTY ON policy.PolicyHistory (EvaluationResults)
USING XML INDEX IX_EvaluationResults
FOR PROPERTY
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistory]’) AND name = N’IX_EvaluatedPolicy’)
DROP INDEX IX_EvaluatedPolicy ON policy.PolicyHistory
GO
CREATE INDEX IX_EvaluatedPolicy ON policy.PolicyHistory(EvaluatedPolicy)
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistory]’) AND name = N’IX_EvaluatedServer’)
DROP INDEX IX_EvaluatedServer ON policy.PolicyHistory
GO
CREATE INDEX IX_EvaluatedServer ON [policy].PolicyHistory
INCLUDE ([PolicyHistoryID],[EvaluationDateTime],[EvaluatedPolicy])
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistory]’) AND name = N’IX_EvaluationDateTime’)
DROP INDEX IX_EvaluationDateTime ON policy.PolicyHistory
GO
CREATE INDEX IX_EvaluationDateTime ON policy.PolicyHistory (EvaluationDateTime)
GO
–Create the table to store the error information from the failed PowerShell executions.
IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = N’U’ AND name = N’EvaluationErrorHistory’)
BEGIN
CREATE TABLE [policy].[EvaluationErrorHistory](
[ErrorHistoryID] [int] IDENTITY(1,1) NOT NULL,
[EvaluatedServer] nvarchar NULL,
[EvaluationDateTime] [datetime] NULL,
[EvaluatedPolicy] nvarchar NULL,
[EvaluationResults] nvarchar NOT NULL,
CONSTRAINT PK_EvaluationErrorHistory PRIMARY KEY CLUSTERED ([ErrorHistoryID] ASC)
)
ALTER TABLE [policy].[EvaluationErrorHistory] ADD CONSTRAINT [DF_EvaluationErrorHistory_EvaluationDateTime] DEFAULT (getdate()) FOR [EvaluationDateTime]
END
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = N’IX_EvaluationErrorHistoryView’)
DROP INDEX IX_EvaluationErrorHistoryView ON policy.EvaluationErrorHistory
GO
CREATE INDEX [IX_EvaluationErrorHistoryView] ON policy.EvaluationErrorHistory ([EvaluatedPolicy] ASC, [EvaluatedServer] ASC, [EvaluationDateTime] DESC)
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = N’IX_EvaluationErrorHistoryPurge’)
DROP INDEX IX_EvaluationErrorHistoryPurge ON policy.EvaluationErrorHistory
GO
CREATE INDEX [IX_EvaluationErrorHistoryPurge] ON policy.EvaluationErrorHistory ([EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = ‘Stat_EvaluatedPolicy_ErrorHistoryID_EvaluatedServer’ )
DROP STATISTICS policy.[EvaluationErrorHistory].[Stat_EvaluatedPolicy_ErrorHistoryID_EvaluatedServer]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_ErrorHistoryID_EvaluatedServer] ON [policy].[EvaluationErrorHistory]([EvaluatedPolicy], [ErrorHistoryID], [EvaluatedServer])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = ‘Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime’ )
DROP STATISTICS policy.[EvaluationErrorHistory].[Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_ErrorHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy] ON [policy].[EvaluationErrorHistory]([ErrorHistoryID], [EvaluatedServer], [EvaluationDateTime], [EvaluatedPolicy])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = ‘Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime’ )
DROP STATISTICS policy.[EvaluationErrorHistory].[Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_ErrorHistoryID_EvaluatedServer_EvaluationDateTime] ON [policy].[EvaluationErrorHistory]([ErrorHistoryID], [EvaluatedServer], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = ‘Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime’ )
DROP STATISTICS policy.[EvaluationErrorHistory].[Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_ErrorHistoryID_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime] ON [policy].[EvaluationErrorHistory]([ErrorHistoryID], [EvaluatedPolicy], [EvaluatedServer], [EvaluationDateTime])
GO
–Create the table to store the policy result details.
–This table is loaded with the procedure policy.epm_LoadPolicyHistoryDetail or through the SQL Server SSIS policy package.
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND type in (N’U’))
BEGIN
CREATE TABLE [policy].[PolicyHistoryDetail](
[PolicyHistoryDetailID] [int] IDENTITY NOT NULL,
[PolicyHistoryID] [int] NULL,
[EvaluatedServer] nvarchar NULL,
[EvaluationDateTime] [datetime] NULL,
[MonthYear] nvarchar NULL,
[EvaluatedPolicy] nvarchar NULL,
[policy_id] [int] NULL,
[CategoryName] nvarchar NULL,
[EvaluatedObject] nvarchar NULL,
[PolicyResult] nvarchar NOT NULL,
[ExceptionMessage] nvarchar NULL,
[ResultDetail] [xml] NULL,
[PolicyHistorySource] nvarchar NOT NULL,
CONSTRAINT PK_PolicyHistoryDetail PRIMARY KEY CLUSTERED ([PolicyHistoryDetailID])
)
END
GO
ALTER TABLE policy.PolicyHistoryDetail ADD CONSTRAINT
FK_PolicyHistoryDetail_PolicyHistory FOREIGN KEY
(PolicyHistoryID) REFERENCES policy.PolicyHistory
(PolicyHistoryID)
ON UPDATE CASCADE
ON DELETE CASCADE
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’FK_PolicyHistoryID’)
DROP INDEX FK_PolicyHistoryID ON policy.PolicyHistoryDetail
GO
CREATE INDEX FK_PolicyHistoryID ON [policy].PolicyHistoryDetail
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_EvaluatedPolicy’)
DROP INDEX IX_EvaluatedPolicy ON policy.PolicyHistoryDetail
GO
CREATE INDEX IX_EvaluatedPolicy ON [policy].PolicyHistoryDetail
INCLUDE ([PolicyHistoryID], [EvaluatedServer], [EvaluationDateTime], [MonthYear], [policy_id], [CategoryName], [EvaluatedObject], [PolicyResult])
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_PolicyHistoryView’)
DROP INDEX IX_PolicyHistoryView ON policy.PolicyHistoryDetail
GO
CREATE INDEX [IX_PolicyHistoryView] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy] ASC, [EvaluatedServer] ASC, [EvaluatedObject] ASC, [EvaluationDateTime] DESC, [PolicyResult] ASC, [policy_id] ASC, CategoryName, MonthYear)
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_PolicyHistoryView_2′)
DROP INDEX IX_PolicyHistoryView_2 ON policy.PolicyHistoryDetail
GO
CREATE INDEX [IX_PolicyHistoryView_2] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy] ASC ,[EvaluatedServer] ASC ,[EvaluationDateTime] ASC)
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_EvaluatedServer_EvaluatedPolicy_EvaluatedObject_EvaluationDateTime’)
DROP INDEX IX_EvaluatedServer_EvaluatedPolicy_EvaluatedObject_EvaluationDateTime ON policy.PolicyHistoryDetail
GO
CREATE INDEX [IX_EvaluatedServer_EvaluatedPolicy_EvaluatedObject_EvaluationDateTime] ON [policy].[PolicyHistoryDetail] ([EvaluatedServer] ASC, [EvaluatedPolicy] ASC, [EvaluatedObject] ASC, [EvaluationDateTime] ASC)
INCLUDE ([PolicyResult])
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_EvaluatedPolicy_MonthYear’)
DROP INDEX IX_EvaluatedPolicy_MonthYear ON policy.PolicyHistoryDetail
GO
CREATE INDEX IX_EvaluatedPolicy_MonthYear ON [policy].PolicyHistoryDetail
INCLUDE (EvaluationDateTime)
GO
–CREATE INDEX IX_CategoryName_EvaluatedPolicy ON [policy].PolicyHistoryDetail
–GO
–CREATE INDEX IX_EvaluatedPolicy_CategoryName ON [policy].PolicyHistoryDetail
–GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_EvaluatedPolicy_EvalDateTime_CategoryName’)
DROP INDEX IX_EvaluatedPolicy_EvalDateTime_CategoryName ON policy.PolicyHistoryDetail
GO
CREATE INDEX IX_EvaluatedPolicy_EvalDateTime_CategoryName ON [policy].PolicyHistoryDetail
INCLUDE ([PolicyHistoryDetailID],[MonthYear],[PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_EvaluatedServer_EvaluationDateTime] ON [policy].[PolicyHistoryDetail] ([EvaluatedServer], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_CategoryName]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_CategoryName] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_EvaluationDateTime] ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluationDateTime_EvaluatedPolicy’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluationDateTime_EvaluatedPolicy]
GO
CREATE STATISTICS [Stat_EvaluationDateTime_EvaluatedPolicy] ON [policy].[PolicyHistoryDetail]([EvaluationDateTime], [EvaluatedPolicy])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_CategoryName_EvaluatedServer’)
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_CategoryName_EvaluatedServer]
GO
CREATE STATISTICS [Stat_CategoryName_EvaluatedServer] ON [policy].[PolicyHistoryDetail] ([CategoryName], [EvaluatedServer])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyResult_EvaluatedServer’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyResult_EvaluatedServer]
GO
CREATE STATISTICS [Stat_PolicyResult_EvaluatedServer] ON [policy].[PolicyHistoryDetail] ([PolicyResult], [EvaluatedServer])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluatedServer_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluatedServer_CategoryName]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_EvaluatedServer_CategoryName] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy], [EvaluatedServer], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_PolicyResult_CategoryName’)
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_PolicyResult_CategoryName]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_PolicyResult_CategoryName] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy], [PolicyResult], [EvaluatedServer])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyResult_PolicyHistoryID_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyResult_PolicyHistoryID_CategoryName]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyResult_PolicyHistoryID_CategoryName] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy], [EvaluatedServer], [EvaluationDateTime], [PolicyResult], [PolicyHistoryID], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_CategoryName_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_CategoryName_PolicyResult]
GO
CREATE STATISTICS Stat_CategoryName_PolicyResult ON [policy].[PolicyHistoryDetail]([CategoryName], [PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer_PolicyHistoryDetailID_EvaluatedPolicy’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer_PolicyHistoryDetailID_EvaluatedPolicy]
GO
CREATE STATISTICS Stat_EvaluatedServer_PolicyHistoryDetailID_EvaluatedPolicy ON [policy].[PolicyHistoryDetail]([EvaluatedServer], [PolicyHistoryDetailID], [EvaluatedPolicy])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_CategoryName_PolicyResult_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_CategoryName_PolicyResult_EvaluationDateTime]
GO
CREATE STATISTICS Stat_EvaluatedPolicy_CategoryName_PolicyResult_EvaluationDateTime ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [CategoryName], [PolicyResult], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluatedServer_PolicyHistoryDetailID_CategoryName_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluatedServer_PolicyHistoryDetailID_CategoryName_PolicyResult]
GO
CREATE STATISTICS Stat_EvaluatedPolicy_EvaluatedServer_PolicyHistoryDetailID_CategoryName_PolicyResult ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [EvaluatedServer], [PolicyHistoryDetailID], [CategoryName], [PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer_CategoryName_PolicyResult_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer_CategoryName_PolicyResult_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID]
GO
CREATE STATISTICS Stat_EvaluatedServer_CategoryName_PolicyResult_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID ON [policy].[PolicyHistoryDetail]([EvaluatedServer], [CategoryName], [PolicyResult], [EvaluatedPolicy], [EvaluationDateTime], [PolicyHistoryDetailID])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime] ON [policy].[PolicyHistoryDetail]([CategoryName], [EvaluatedPolicy], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_CategoryName]
GO
CREATE STATISTICS [Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_CategoryName] ON [policy].[PolicyHistoryDetail]([PolicyHistoryID], [EvaluatedServer], [EvaluationDateTime], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer_EvaluatedServer_EvaluationDateTime_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer_EvaluatedServer_EvaluationDateTime_PolicyResult]
GO
CREATE STATISTICS [Stat_EvaluatedServer_EvaluatedServer_EvaluationDateTime_PolicyResult] ON [policy].[PolicyHistoryDetail]([EvaluatedServer], [EvaluatedObject], [EvaluationDateTime], [PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_1_EvaluatedServer_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_1_EvaluatedServer_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_1_EvaluatedServer_EvaluationDateTime] ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [PolicyHistoryDetailID], [EvaluatedServer], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluationDateTime_EvaluatedPolicy_PolicyHistoryDetailID_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluationDateTime_EvaluatedPolicy_PolicyHistoryDetailID_PolicyResult]
GO
CREATE STATISTICS [Stat_EvaluationDateTime_EvaluatedPolicy_PolicyHistoryDetailID_PolicyResult] ON [policy].[PolicyHistoryDetail]([EvaluationDateTime], [EvaluatedPolicy], [PolicyHistoryDetailID], [PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyResult_EvaluatedPolicy_PolicyHistoryDetailID_EvaluatedServer’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyResult_EvaluatedPolicy_PolicyHistoryDetailID_EvaluatedServer]
GO
CREATE STATISTICS [Stat_PolicyResult_EvaluatedPolicy_PolicyHistoryDetailID_EvaluatedServer] ON [policy].[PolicyHistoryDetail]([PolicyResult], [EvaluatedPolicy], [PolicyHistoryDetailID], [EvaluatedServer])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyHistoryDetailID_PolicyHistoryID_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyHistoryDetailID_PolicyHistoryID_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_PolicyHistoryDetailID_PolicyHistoryID_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime] ON [policy].[PolicyHistoryDetail]([PolicyHistoryDetailID], [PolicyHistoryID], [EvaluatedPolicy], [EvaluatedServer], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id]
GO
CREATE STATISTICS [Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id] ON [policy].[PolicyHistoryDetail]([PolicyHistoryID], [EvaluatedServer], [EvaluationDateTime], [EvaluatedPolicy], [policy_id])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id_CategoryName_PolicyHistoryID’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id_CategoryName_PolicyHistoryID]
GO
CREATE STATISTICS [Stat_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id_CategoryName_PolicyHistoryID] ON [policy].[PolicyHistoryDetail]([EvaluatedServer], [EvaluationDateTime], [EvaluatedPolicy], [policy_id], [CategoryName], [PolicyHistoryID])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyHistoryDetailID_policy_id_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyHistoryDetailID_policy_id_CategoryName]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyHistoryDetailID_policy_id_CategoryName] ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [PolicyResult], [EvaluatedServer], [EvaluationDateTime], [PolicyHistoryDetailID], [policy_id], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluatedServer_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID_PolicyHistoryID’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluatedServer_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID_PolicyHistoryID]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_EvaluatedServer_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID_PolicyHistoryID] ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [EvaluatedServer], [PolicyResult], [EvaluationDateTime], [PolicyHistoryDetailID], [PolicyHistoryID], [policy_id], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluationDateTime_EvaluatedPolicy_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluationDateTime_EvaluatedPolicy_PolicyResult]
GO
CREATE STATISTICS [Stat_EvaluationDateTime_EvaluatedPolicy_PolicyResult] ON [policy].[PolicyHistoryDetail]([EvaluationDateTime], [EvaluatedPolicy], [PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_CategoryName]
GO
CREATE STATISTICS [Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_CategoryName] ON [policy].[PolicyHistoryDetail]([PolicyHistoryID], [EvaluatedServer], [EvaluationDateTime], [EvaluatedPolicy], [CategoryName])
GO
–Create the function to support server selection.
–The following function will support nested CMS folders for the EPM Framework.
–The function must be created in a database ON the CMS server.
–This database will also store the policy history.
USE $(ManagementDatabase)
GO
IF EXISTS(SELECT * FROM sys.objects WHERE name = ‘pfn_ServerGroupInstances’ AND type = ‘TF’)
DROP FUNCTION policy.pfn_ServerGroupInstances
GO
CREATE FUNCTION [policy].[pfn_ServerGroupInstances] (@server_group_name NVARCHAR(128))
RETURNS TABLE
AS
RETURN(WITH ServerGroups(parent_id, server_group_id, name) AS
(
SELECT parent_id, server_group_id, name
FROM msdb.dbo.sysmanagement_shared_server_groups tg
WHERE is_system_object = 0
AND (tg.name = @server_group_name OR @server_group_name = ”)
UNION ALL
SELECT cg.parent_id, cg.server_group_id, cg.name
FROM msdb.dbo.sysmanagement_shared_server_groups cg
INNER JOIN ServerGroups pg ON cg.parent_id = pg.server_group_id
)
SELECT s.server_name, sg.name AS GroupName
FROM [msdb].[dbo].[sysmanagement_shared_registered_servers_internal] s
INNER JOIN ServerGroups SG ON s.server_group_id = sg.server_group_id
)
GO
/*
CREATE FUNCTION policy.pfn_ServerGroupInstances (@server_group_name NVARCHAR(128))
RETURNS @ServerGroups TABLE (server_name nvarchar(128), GroupName nvarchar(128))
AS
BEGIN
IF @server_group_name = ”
BEGIN
INSERT @ServerGroups
SELECT s.server_name, ssg.name AS GroupName
FROM [msdb].[dbo].[sysmanagement_shared_registered_servers_internal] s
INNER JOIN msdb.dbo.sysmanagement_shared_server_groups ssg
ON s.server_group_id = ssg.server_group_id
END
ELSE
WITH ServerGroups(parent_id, server_group_id, name) AS
(
SELECT parent_id, server_group_id, name
FROM msdb.dbo.sysmanagement_shared_server_groups tg
WHERE is_system_object = 0
AND (tg.name = @server_group_name OR @server_group_name = ”)
UNION ALL
SELECT cg.parent_id, cg.server_group_id, cg.name
FROM msdb.dbo.sysmanagement_shared_server_groups cg
INNER JOIN ServerGroups pg ON cg.parent_id = pg.server_group_id
)
INSERT @ServerGroups
SELECT s.server_name, sg.name AS GroupName
FROM [msdb].[dbo].[sysmanagement_shared_registered_servers_internal] s
INNER JOIN ServerGroups SG ON s.server_group_id = sg.server_group_id
RETURN
END
GO
*/
–Create the views which are used in the policy reports
–Drop the view if it exists.
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_ServerGroups]’))
DROP VIEW [policy].[v_ServerGroups]
GO
CREATE VIEW policy.v_ServerGroups AS
WITH ServerGroups(parent_id, server_group_id, GroupName, GroupLevel, Sort, GroupValue)
AS
(SELECT parent_id
, server_group_id
, CAST(‘ALL’ AS varchar(500))
, 1 AS GroupLevel
, CAST(‘ALL’ AS varchar(500)) AS Sort
, CAST(” AS varchar(255)) AS GroupValue
FROM msdb.dbo.sysmanagement_shared_server_groups tg
WHERE server_type = 0 AND parent_id IS NULL
UNION ALL
SELECT cg.parent_id
, cg.server_group_id
, CAST(REPLICATE(‘ ‘, GroupLevel) + cg.name AS varchar(500))
, GroupLevel + 1
, CAST(Sort + ‘ | ‘ + cg.name AS varchar(500)) AS Sort
, CAST(name AS varchar(255)) AS GroupValue
FROM msdb.dbo.sysmanagement_shared_server_groups cg
INNER JOIN ServerGroups pg ON cg.parent_id = pg.server_group_id)
SELECT parent_id, server_group_id, GroupName, GroupLevel, Sort, GroupValue
FROM ServerGroups
GO
–Drop the view if it exists.
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_PolicyHistory]’))
DROP VIEW [policy].[v_PolicyHistory]
GO
CREATE VIEW [policy].[v_PolicyHistory]
AS
–The policy.v_PolicyHistory view will return all results
–and identify the policy evaluation result AS PASS, FAIL, or
–ERROR. The ERROR result indicates that the policy was not able
–to evaluate against an object.
SELECT PH.PolicyHistoryID
, PH.EvaluatedServer
, PH.EvaluationDateTime
, PH.EvaluatedPolicy
, PH.PolicyResult
, PH.ExceptionMessage
, PH.ResultDetail
, PH.EvaluatedObject
, PH.policy_id
, PH.CategoryName
, PH.MonthYear
FROM policy.PolicyHistoryDetail PH
INNER JOIN msdb.dbo.syspolicy_policies AS p ON p.name = PH.EvaluatedPolicy
–INNER JOIN msdb.dbo.syspolicy_policy_categories AS c ON p.policy_category_id = c.policy_category_id
AND PH.EvaluatedPolicy NOT IN (SELECT spp.name
FROM msdb.dbo.syspolicy_policies spp
INNER JOIN msdb.dbo.syspolicy_policy_categories spc ON spp.policy_category_id = spc.policy_category_id
WHERE spc.name = ‘Disabled’)
GO
–Drop the view if it exists.
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_PolicyHistory_Rank]’))
DROP VIEW policy.v_PolicyHistory_Rank
GO
CREATE VIEW policy.v_PolicyHistory_Rank
AS
SELECT PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluatedObject
, PolicyResult
, ResultDetail
, ExceptionMessage
, policy_id
, CategoryName
, MonthYear
, DENSE_RANK() OVER (
PARTITION BY EvaluatedPolicy, EvaluatedServer, EvaluatedObject
ORDER BY EvaluationDateTime DESC) AS EvaluationOrderDesc
FROM policy.v_PolicyHistory VPH
GO
–Drop the view if it exists.
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_PolicyHistory_LastEvaluation]’))
DROP VIEW policy.v_PolicyHistory_LastEvaluation
GO
CREATE VIEW policy.v_PolicyHistory_LastEvaluation
AS
–The policy.v_PolicyHistory_LastEvaluation view will the last result for any given policy evaluated against an object.
–This view requires the v_PolicyHistory view exist.
SELECT PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluatedObject
, PolicyResult
, ResultDetail
, ExceptionMessage
, policy_id
, CategoryName
, MonthYear
, EvaluationOrderDesc
FROM policy.v_PolicyHistory_Rank VPH
WHERE EvaluationOrderDesc = 1
AND NOT EXISTS(
SELECT *
FROM policy.PolicyHistoryDetail PH
WHERE PH.EvaluatedPolicy = VPH.EvaluatedPolicy
AND PH.EvaluatedServer = VPH.EvaluatedServer
AND PH.EvaluationDateTime > VPH.EvaluationDateTime)
GO
–Create a view to return all errors.
–Errors will be returned from the table EvaluationErrorHistory and the errors in the PolicyHistory table.
–Drop the view if it exists.
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_EvaluationErrorHistory]’))
DROP VIEW policy.v_EvaluationErrorHistory
GO
CREATE VIEW policy.v_EvaluationErrorHistory
AS
SELECT EEH.ErrorHistoryID
, EEH.EvaluatedServer
, EEH.EvaluationDateTime
, EEH.EvaluatedPolicy
, CASE WHEN CHARINDEX(‘\’, EEH.EvaluatedServer) > 0
THEN RIGHT(EEH.EvaluatedServer, CHARINDEX(‘\’, REVERSE(EEH.EvaluatedServer)) – 1)
ELSE EEH.EvaluatedServer
END
AS EvaluatedObject
, EEH.EvaluationResults
, p.policy_id
, c.name AS CategoryName
, DATENAME(month, EvaluationDateTime) + ‘ ‘ + datename(year, EvaluationDateTime) AS MonthYear
, ‘ERROR’ AS PolicyResult
FROM policy.EvaluationErrorHistory AS EEH
INNER JOIN msdb.dbo.syspolicy_policies AS p ON p.name = EEH.EvaluatedPolicy
INNER JOIN msdb.dbo.syspolicy_policy_categories AS c ON p.policy_category_id = c.policy_category_id
UNION ALL
SELECT PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, CASE WHEN EvaluatedObject != ‘No Targets Found’
THEN RIGHT(EvaluatedObject, CHARINDEX(‘\’, REVERSE(EvaluatedObject)) – 1)
ELSE EvaluatedObject
END
AS EvaluatedObject
, ExceptionMessage
, policy_id
, CategoryName
, MonthYear
, PolicyResult
FROM policy.v_PolicyHistory_LastEvaluation
WHERE PolicyResult = ‘ERROR’
GO
–Create a view to return the last error for each policy against
–an instance.
–Drop the view if it exists.
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_EvaluationErrorHistory_LastEvaluation]’))
DROP VIEW policy.v_EvaluationErrorHistory_LastEvaluation
GO
CREATE VIEW policy.v_EvaluationErrorHistory_LastEvaluation
AS
SELECT ErrorHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, Policy_ID
, EvaluatedObject
, EvaluationResults
, CategoryName
, MonthYear
, PolicyResult
, DENSE_RANK() OVER (
PARTITION BY EvaluatedServer, EvaluatedPolicy
ORDER BY EvaluationDateTime DESC)AS EvaluationOrderDesc
FROM policy.v_EvaluationErrorHistory EEH
WHERE NOT EXISTS (
SELECT *
FROM policy.PolicyHistoryDetail PH
WHERE PH.EvaluatedPolicy = EEH.EvaluatedPolicy
AND PH.EvaluatedServer = EEH.EvaluatedServer
AND PH.EvaluationDateTime > EEH.EvaluationDateTime)
GO
–Create the procedure epm_LoadPolicyHistoryDetail will load the details from the XML documents in PolicyHistory to the PolicyHistoryDetails table.
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[policy].[epm_LoadPolicyHistoryDetail]’) AND type in (N’P’, N’PC’))
DROP PROCEDURE [policy].[epm_LoadPolicyHistoryDetail]
GO
CREATE PROCEDURE policy.epm_LoadPolicyHistoryDetail @PolicyCategoryFilter VARCHAR(255)
AS
SET NOCOUNT ON;
IF @PolicyCategoryFilter = ”
SET @PolicyCategoryFilter = NULL
DECLARE @sqlcmd VARCHAR(8000), @Text NVARCHAR(255), @Remain int
SELECT @Text = CONVERT(varchar, GETDATE(), 9) + ‘ – Starting data integration for ‘ + CASE WHEN @PolicyCategoryFilter IS NULL THEN ‘ALL categories’ ELSE ‘Category ‘ + @PolicyCategoryFilter END
RAISERROR (@Text, 10, 1) WITH NOWAIT;
–Insert the evaluation results.
SELECT @sqlcmd = ‘;WITH XMLNAMESPACES (”http://schemas.microsoft.com/sqlserver/DMF/2007/08” AS DMF)
,cteEval AS (SELECT PH.PolicyHistoryID
, PH.EvaluatedServer
, PH.EvaluationDateTime
, PH.EvaluatedPolicy
, Res.Expr.value(”(../DMF:TargetQueryExpression)[1]”, ”nvarchar(150)”) AS EvaluatedObject
, (CASE WHEN Res.Expr.value(”(../DMF:Result)[1]”, ”nvarchar(150)”) = ”FALSE” AND Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) = ””
THEN ”FAIL”
WHEN Res.Expr.value(”(../DMF:Result)[1]”, ”nvarchar(150)”)= ”FALSE” AND Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) <> ””
THEN ”ERROR”
ELSE ”PASS”
END) AS PolicyResult
, Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) AS ExceptionMessage
, CAST(Expr.value(”(../DMF:ResultDetail)[1]”, ”nvarchar(max)”)AS XML) AS ResultDetail
, p.policy_id
, c.name AS CategoryName
, datename(month, EvaluationDateTime) + ” ” + datename(year, EvaluationDateTime) AS MonthYear
, ”PowerShell EPM Framework” AS PolicyHistorySource
, DENSE_RANK() OVER (PARTITION BY Res.Expr.value(”(../DMF:TargetQueryExpression)[1]”, ”nvarchar(150)”) ORDER BY Expr) AS [TopRank]
FROM policy.PolicyHistory AS PH
INNER JOIN msdb.dbo.syspolicy_policies AS p ON p.name = PH.EvaluatedPolicy
INNER JOIN msdb.dbo.syspolicy_policy_categories AS c ON p.policy_category_id = c.policy_category_id
CROSS APPLY EvaluationResults.nodes(”declare default element namespace “http://schemas.microsoft.com/sqlserver/DMF/2007/08”;
//TargetQueryExpression”
) AS Res(Expr)
WHERE NOT EXISTS (SELECT DISTINCT PHD.PolicyHistoryID FROM policy.PolicyHistoryDetail PHD WITH(NOLOCK) WHERE PHD.PolicyHistoryID = PH.PolicyHistoryID AND PHD.ResultDetail IS NOT NULL)
‘ + CASE WHEN @PolicyCategoryFilter IS NULL THEN ” ELSE ‘AND c.name = ”’ + @PolicyCategoryFilter + ”” END + ‘
AND EvaluationResults.exist(”declare namespace DMF=”http://schemas.microsoft.com/sqlserver/DMF/2007/08″;
//DMF:EvaluationDetail”) = 1)
INSERT INTO policy.PolicyHistoryDetail (
PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluatedObject
, PolicyResult
, ExceptionMessage
, ResultDetail
, policy_id
, CategoryName
, MonthYear
, PolicyHistorySource
)
SELECT PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluatedObject
, PolicyResult
, ExceptionMessage
, ResultDetail
, policy_id
, CategoryName
, MonthYear
, PolicyHistorySource
FROM cteEval
WHERE cteEval.[TopRank] = 1′; — Remove duplicates
EXEC (@sqlcmd);
SELECT @Text = CONVERT(NVARCHAR, GETDATE(), 9) + ‘ |- ‘ + CONVERT(NVARCHAR, @@ROWCOUNT) + ‘ rows inserted…’
RAISERROR (@Text, 10, 1) WITH NOWAIT;
SELECT @Text = CONVERT(varchar, GETDATE(), 9) + ‘ – Starting no target data integration’
RAISERROR (@Text, 10, 1) WITH NOWAIT;
–Insert the policies that evaluated with no target
SELECT @sqlcmd = ‘;WITH XMLNAMESPACES (”http://schemas.microsoft.com/sqlserver/DMF/2007/08” AS DMF)
INSERT INTO policy.PolicyHistoryDetail (
PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluatedObject
, PolicyResult
, ExceptionMessage
, ResultDetail
, policy_id
, CategoryName
, MonthYear
, PolicyHistorySource
)
SELECT PH.PolicyHistoryID
, PH.EvaluatedServer
, PH.EvaluationDateTime
, PH.EvaluatedPolicy
, ”No Targets Found” AS EvaluatedObject
, (CASE WHEN Res.Expr.value(”(../DMF:Result)[1]”, ”nvarchar(150)”)= ”FALSE” AND Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) = ””
THEN ”FAIL”
WHEN Res.Expr.value(”(../DMF:Result)[1]”, ”nvarchar(150)”)= ”FALSE” AND Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”)<> ””
THEN ”ERROR”
ELSE ”PASS”
END) AS PolicyResult
, Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) AS ExceptionMessage
, NULL AS ResultDetail
, p.policy_id
, c.name AS CategoryName
, datename(month, EvaluationDateTime) + ” ” + datename(year, EvaluationDateTime) AS MonthYear
, ”PowerShell EPM Framework”
FROM policy.PolicyHistory AS PH
INNER JOIN msdb.dbo.syspolicy_policies AS p ON p.name = PH.EvaluatedPolicy
INNER JOIN msdb.dbo.syspolicy_policy_categories AS c ON p.policy_category_id = c.policy_category_id
CROSS APPLY EvaluationResults.nodes(”declare default element namespace “http://schemas.microsoft.com/sqlserver/DMF/2007/08”;
//DMF:ServerInstance”
) AS Res(Expr)
WHERE NOT EXISTS (SELECT DISTINCT PHD.PolicyHistoryID FROM policy.PolicyHistoryDetail PHD WITH(NOLOCK) WHERE PHD.PolicyHistoryID = PH.PolicyHistoryID AND PHD.ResultDetail IS NULL)
‘ + CASE WHEN @PolicyCategoryFilter IS NULL THEN ” ELSE ‘AND c.name = ”’ + @PolicyCategoryFilter + ”” END + ‘
AND EvaluationResults.exist(”declare namespace DMF=”http://schemas.microsoft.com/sqlserver/DMF/2007/08″;
//DMF:EvaluationDetail”) = 0
ORDER BY DENSE_RANK() OVER (ORDER BY Expr);’ — Remove duplicates
EXEC (@sqlcmd);
SELECT @Text = CONVERT(NVARCHAR, GETDATE(), 9) + ‘ |- ‘ + CONVERT(NVARCHAR, @@ROWCOUNT) + ‘ rows inserted…’
RAISERROR (@Text, 10, 1) WITH NOWAIT;
SELECT @Text = CONVERT(varchar, GETDATE(), 9) + ‘ – Starting errors data integration’
RAISERROR (@Text, 10, 1) WITH NOWAIT;
–Insert the error records
SELECT @sqlcmd = ‘;WITH XMLNAMESPACES (”http://schemas.microsoft.com/sqlserver/DMF/2007/08” AS DMF)
INSERT INTO policy.EvaluationErrorHistory(
EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluationResults
)
SELECT PH.EvaluatedServer
, PH.EvaluationDateTime
, PH.EvaluatedPolicy
, Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) AS ExceptionMessage
FROM policy.PolicyHistory AS PH
INNER JOIN msdb.dbo.syspolicy_policies AS p ON p.name = PH.EvaluatedPolicy
INNER JOIN msdb.dbo.syspolicy_policy_categories AS c ON p.policy_category_id = c.policy_category_id
CROSS APPLY EvaluationResults.nodes(”declare default element namespace “http://schemas.microsoft.com/sqlserver/DMF/2007/08”;
//DMF:ServerInstance”
) AS Res(Expr)
WHERE PH.PolicyHistoryID NOT IN (SELECT DISTINCT PH.PolicyHistoryID FROM policy.EvaluationErrorHistory AS PHD WITH(NOLOCK) INNER JOIN policy.PolicyHistory AS PH WITH(NOLOCK) ON PH.EvaluatedServer = PHD.EvaluatedServer AND PH.EvaluationDateTime = PHD.EvaluationDateTime AND PH.EvaluatedPolicy = PHD.EvaluatedPolicy)
‘ + CASE WHEN @PolicyCategoryFilter IS NULL THEN ” ELSE ‘AND c.name = ”’ + @PolicyCategoryFilter + ”” END + ‘
AND Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) <> ””
–AND Res.Expr.value(”(../DMF:Result)[1]”, ”nvarchar(150)”) = ”FALSE”
ORDER BY DENSE_RANK() OVER (ORDER BY Expr);’ — Remove duplicates
EXEC (@sqlcmd);
SELECT @Text = CONVERT(NVARCHAR, GETDATE(), 9) + ‘ |- ‘ + CONVERT(NVARCHAR, @@ROWCOUNT) + ‘ rows inserted…’
RAISERROR (@Text, 10, 1) WITH NOWAIT;
SELECT @Text = CONVERT(varchar, GETDATE(), 9) + ‘ – Finished data integration for ‘ + CASE WHEN @PolicyCategoryFilter IS NULL THEN ‘ALL categories’ ELSE ‘Category ‘ + @PolicyCategoryFilter END
RAISERROR (@Text, 10, 1) WITH NOWAIT;
GO
USE $(ManagementDatabase)
GO
EXEC policy.epm_LoadPolicyHistoryDetail NULL
GO
USE $(ManagementDatabase)
GO
IF (SELECT SERVERPROPERTY(‘EditionID’)) IN (1804890536, 1872460670, 610778273, -2117995310) — Supports Enterprise only features
BEGIN
ALTER INDEX [PK_EvaluationErrorHistory] ON [policy].[EvaluationErrorHistory] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE)
ALTER INDEX [PK_PolicyHistoryDetail] ON [policy].[PolicyHistoryDetail] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE)
ALTER INDEX [PK_PolicyHistory] ON [policy].[PolicyHistory] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE)
END;
GO
EPM_Upgrade_Database_Objects
/*
SQLCMD script to upgrade changed objects from previous deployment of a centralized Policy-Based Management solution.
Set the variables to define the server and database which stores the policy results.
*/
:SETVAR ServerName “SYBENG01”
:SETVAR ManagementDatabase “dbDooT”
GO
:CONNECT $(ServerName)
GO
–Drop old indexes and stats
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_EvaluatedServer’)
DROP INDEX IX_EvaluatedServer ON policy.PolicyHistoryDetail
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer]
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy]
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_CategoryName’)
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_CategoryName]
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyResult]
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_Policy_Server_Category’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_Policy_Server_Category]
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_Policy_Result_Server’)
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_Policy_Result_Server]
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_Covered’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_Covered]
GO
–Start create new indexes and stats
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistory]’) AND name = N’IX_EvaluationDateTime’)
DROP INDEX IX_EvaluationDateTime ON policy.PolicyHistory
GO
CREATE INDEX IX_EvaluationDateTime ON policy.PolicyHistory (EvaluationDateTime)
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = N’IX_EvaluationErrorHistoryPurge’)
DROP INDEX IX_EvaluationErrorHistoryPurge ON policy.EvaluationErrorHistory
GO
CREATE INDEX [IX_EvaluationErrorHistoryPurge] ON policy.EvaluationErrorHistory ([EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = ‘Stat_EvaluatedPolicy_ErrorHistoryID_EvaluatedServer’ )
DROP STATISTICS policy.[EvaluationErrorHistory].[Stat_EvaluatedPolicy_ErrorHistoryID_EvaluatedServer]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_ErrorHistoryID_EvaluatedServer] ON [policy].[EvaluationErrorHistory]([EvaluatedPolicy], [ErrorHistoryID], [EvaluatedServer])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = ‘Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime’ )
DROP STATISTICS policy.[EvaluationErrorHistory].[Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_ErrorHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy] ON [policy].[EvaluationErrorHistory]([ErrorHistoryID], [EvaluatedServer], [EvaluationDateTime], [EvaluatedPolicy])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = ‘Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime’ )
DROP STATISTICS policy.[EvaluationErrorHistory].[Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_ErrorHistoryID_EvaluatedServer_EvaluationDateTime] ON [policy].[EvaluationErrorHistory]([ErrorHistoryID], [EvaluatedServer], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[EvaluationErrorHistory]’) AND name = ‘Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime’ )
DROP STATISTICS policy.[EvaluationErrorHistory].[Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_ErrorHistoryID_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime] ON [policy].[EvaluationErrorHistory]([ErrorHistoryID], [EvaluatedPolicy], [EvaluatedServer], [EvaluationDateTime])
GO
ALTER TABLE policy.PolicyHistoryDetail ADD CONSTRAINT
FK_PolicyHistoryDetail_PolicyHistory FOREIGN KEY
(PolicyHistoryID) REFERENCES policy.PolicyHistory
(PolicyHistoryID)
ON UPDATE CASCADE
ON DELETE CASCADE
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’FK_PolicyHistoryID’)
DROP INDEX FK_PolicyHistoryID ON policy.PolicyHistoryDetail
GO
CREATE INDEX FK_PolicyHistoryID ON [policy].PolicyHistoryDetail
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_PolicyHistoryView_2′)
DROP INDEX IX_PolicyHistoryView_2 ON policy.PolicyHistoryDetail
GO
CREATE INDEX [IX_PolicyHistoryView_2] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy] ASC ,[EvaluatedServer] ASC ,[EvaluationDateTime] ASC)
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_EvaluatedServer_EvaluatedPolicy_EvaluatedObject_EvaluationDateTime’)
DROP INDEX IX_EvaluatedServer_EvaluatedPolicy_EvaluatedObject_EvaluationDateTime ON policy.PolicyHistoryDetail
GO
CREATE INDEX [IX_EvaluatedServer_EvaluatedPolicy_EvaluatedObject_EvaluationDateTime] ON [policy].[PolicyHistoryDetail] ([EvaluatedServer] ASC, [EvaluatedPolicy] ASC, [EvaluatedObject] ASC, [EvaluationDateTime] ASC)
INCLUDE ([PolicyResult])
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_EvaluatedPolicy_MonthYear’)
DROP INDEX IX_EvaluatedPolicy_MonthYear ON policy.PolicyHistoryDetail
GO
CREATE INDEX IX_EvaluatedPolicy_MonthYear ON [policy].PolicyHistoryDetail
INCLUDE (EvaluationDateTime)
GO
–CREATE INDEX IX_CategoryName_EvaluatedPolicy ON [policy].PolicyHistoryDetail
–GO
–CREATE INDEX IX_EvaluatedPolicy_CategoryName ON [policy].PolicyHistoryDetail
–GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = N’IX_EvaluatedPolicy_EvalDateTime_CategoryName’)
DROP INDEX IX_EvaluatedPolicy_EvalDateTime_CategoryName ON policy.PolicyHistoryDetail
GO
CREATE INDEX IX_EvaluatedPolicy_EvalDateTime_CategoryName ON [policy].PolicyHistoryDetail
INCLUDE ([PolicyHistoryDetailID],[MonthYear],[PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_EvaluatedServer_EvaluationDateTime] ON [policy].[PolicyHistoryDetail] ([EvaluatedServer], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_CategoryName]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_CategoryName] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_EvaluationDateTime] ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluationDateTime_EvaluatedPolicy’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluationDateTime_EvaluatedPolicy]
GO
CREATE STATISTICS [Stat_EvaluationDateTime_EvaluatedPolicy] ON [policy].[PolicyHistoryDetail]([EvaluationDateTime], [EvaluatedPolicy])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_CategoryName_EvaluatedServer’)
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_CategoryName_EvaluatedServer]
GO
CREATE STATISTICS [Stat_CategoryName_EvaluatedServer] ON [policy].[PolicyHistoryDetail] ([CategoryName], [EvaluatedServer])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyResult_EvaluatedServer’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyResult_EvaluatedServer]
GO
CREATE STATISTICS [Stat_PolicyResult_EvaluatedServer] ON [policy].[PolicyHistoryDetail] ([PolicyResult], [EvaluatedServer])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluatedServer_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluatedServer_CategoryName]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_EvaluatedServer_CategoryName] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy], [EvaluatedServer], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_PolicyResult_CategoryName’)
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_PolicyResult_CategoryName]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_PolicyResult_CategoryName] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy], [PolicyResult], [EvaluatedServer])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyResult_PolicyHistoryID_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyResult_PolicyHistoryID_CategoryName]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyResult_PolicyHistoryID_CategoryName] ON [policy].[PolicyHistoryDetail] ([EvaluatedPolicy], [EvaluatedServer], [EvaluationDateTime], [PolicyResult], [PolicyHistoryID], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_CategoryName_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_CategoryName_PolicyResult]
GO
CREATE STATISTICS Stat_CategoryName_PolicyResult ON [policy].[PolicyHistoryDetail]([CategoryName], [PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer_PolicyHistoryDetailID_EvaluatedPolicy’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer_PolicyHistoryDetailID_EvaluatedPolicy]
GO
CREATE STATISTICS Stat_EvaluatedServer_PolicyHistoryDetailID_EvaluatedPolicy ON [policy].[PolicyHistoryDetail]([EvaluatedServer], [PolicyHistoryDetailID], [EvaluatedPolicy])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_CategoryName_PolicyResult_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_CategoryName_PolicyResult_EvaluationDateTime]
GO
CREATE STATISTICS Stat_EvaluatedPolicy_CategoryName_PolicyResult_EvaluationDateTime ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [CategoryName], [PolicyResult], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluatedServer_PolicyHistoryDetailID_CategoryName_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluatedServer_PolicyHistoryDetailID_CategoryName_PolicyResult]
GO
CREATE STATISTICS Stat_EvaluatedPolicy_EvaluatedServer_PolicyHistoryDetailID_CategoryName_PolicyResult ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [EvaluatedServer], [PolicyHistoryDetailID], [CategoryName], [PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer_CategoryName_PolicyResult_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer_CategoryName_PolicyResult_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID]
GO
CREATE STATISTICS Stat_EvaluatedServer_CategoryName_PolicyResult_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID ON [policy].[PolicyHistoryDetail]([EvaluatedServer], [CategoryName], [PolicyResult], [EvaluatedPolicy], [EvaluationDateTime], [PolicyHistoryDetailID])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_CategoryName_EvaluatedPolicy_EvaluationDateTime] ON [policy].[PolicyHistoryDetail]([CategoryName], [EvaluatedPolicy], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_CategoryName]
GO
CREATE STATISTICS [Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_CategoryName] ON [policy].[PolicyHistoryDetail]([PolicyHistoryID], [EvaluatedServer], [EvaluationDateTime], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer_EvaluatedServer_EvaluationDateTime_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer_EvaluatedServer_EvaluationDateTime_PolicyResult]
GO
CREATE STATISTICS [Stat_EvaluatedServer_EvaluatedServer_EvaluationDateTime_PolicyResult] ON [policy].[PolicyHistoryDetail]([EvaluatedServer], [EvaluatedObject], [EvaluationDateTime], [PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_1_EvaluatedServer_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_1_EvaluatedServer_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_1_EvaluatedServer_EvaluationDateTime] ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [PolicyHistoryDetailID], [EvaluatedServer], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluationDateTime_EvaluatedPolicy_PolicyHistoryDetailID_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluationDateTime_EvaluatedPolicy_PolicyHistoryDetailID_PolicyResult]
GO
CREATE STATISTICS [Stat_EvaluationDateTime_EvaluatedPolicy_PolicyHistoryDetailID_PolicyResult] ON [policy].[PolicyHistoryDetail]([EvaluationDateTime], [EvaluatedPolicy], [PolicyHistoryDetailID], [PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyResult_EvaluatedPolicy_PolicyHistoryDetailID_EvaluatedServer’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyResult_EvaluatedPolicy_PolicyHistoryDetailID_EvaluatedServer]
GO
CREATE STATISTICS [Stat_PolicyResult_EvaluatedPolicy_PolicyHistoryDetailID_EvaluatedServer] ON [policy].[PolicyHistoryDetail]([PolicyResult], [EvaluatedPolicy], [PolicyHistoryDetailID], [EvaluatedServer])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyHistoryDetailID_PolicyHistoryID_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyHistoryDetailID_PolicyHistoryID_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime]
GO
CREATE STATISTICS [Stat_PolicyHistoryDetailID_PolicyHistoryID_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime] ON [policy].[PolicyHistoryDetail]([PolicyHistoryDetailID], [PolicyHistoryID], [EvaluatedPolicy], [EvaluatedServer], [EvaluationDateTime])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id]
GO
CREATE STATISTICS [Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id] ON [policy].[PolicyHistoryDetail]([PolicyHistoryID], [EvaluatedServer], [EvaluationDateTime], [EvaluatedPolicy], [policy_id])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id_CategoryName_PolicyHistoryID’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id_CategoryName_PolicyHistoryID]
GO
CREATE STATISTICS [Stat_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_policy_id_CategoryName_PolicyHistoryID] ON [policy].[PolicyHistoryDetail]([EvaluatedServer], [EvaluationDateTime], [EvaluatedPolicy], [policy_id], [CategoryName], [PolicyHistoryID])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyHistoryDetailID_policy_id_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyHistoryDetailID_policy_id_CategoryName]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_EvaluatedPolicy_EvaluatedServer_EvaluationDateTime_PolicyHistoryDetailID_policy_id_CategoryName] ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [PolicyResult], [EvaluatedServer], [EvaluationDateTime], [PolicyHistoryDetailID], [policy_id], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluatedPolicy_EvaluatedServer_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID_PolicyHistoryID’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluatedPolicy_EvaluatedServer_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID_PolicyHistoryID]
GO
CREATE STATISTICS [Stat_EvaluatedPolicy_EvaluatedServer_EvaluatedPolicy_EvaluationDateTime_PolicyHistoryDetailID_PolicyHistoryID] ON [policy].[PolicyHistoryDetail]([EvaluatedPolicy], [EvaluatedServer], [PolicyResult], [EvaluationDateTime], [PolicyHistoryDetailID], [PolicyHistoryID], [policy_id], [CategoryName])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_EvaluationDateTime_EvaluatedPolicy_PolicyResult’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_EvaluationDateTime_EvaluatedPolicy_PolicyResult]
GO
CREATE STATISTICS [Stat_EvaluationDateTime_EvaluatedPolicy_PolicyResult] ON [policy].[PolicyHistoryDetail]([EvaluationDateTime], [EvaluatedPolicy], [PolicyResult])
GO
IF EXISTS(SELECT * FROM sys.stats WHERE object_id = OBJECT_ID(N'[policy].[PolicyHistoryDetail]’) AND name = ‘Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_CategoryName’ )
DROP STATISTICS policy.[PolicyHistoryDetail].[Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_CategoryName]
GO
CREATE STATISTICS [Stat_PolicyHistoryID_EvaluatedServer_EvaluationDateTime_EvaluatedPolicy_CategoryName] ON [policy].[PolicyHistoryDetail]([PolicyHistoryID], [EvaluatedServer], [EvaluationDateTime], [EvaluatedPolicy], [CategoryName])
GO
–Update the function to support server selection.
–The following function will support nested CMS folders for the EPM Framework.
–The function must be created in a database ON the CMS server.
–This database will also store the policy history.
USE $(ManagementDatabase)
GO
IF EXISTS(SELECT * FROM sys.objects WHERE name = ‘pfn_ServerGroupInstances’ AND type = ‘TF’)
DROP FUNCTION policy.pfn_ServerGroupInstances
GO
CREATE FUNCTION [policy].[pfn_ServerGroupInstances] (@server_group_name NVARCHAR(128))
RETURNS TABLE
AS
RETURN(WITH ServerGroups(parent_id, server_group_id, name) AS
(
SELECT parent_id, server_group_id, name
FROM msdb.dbo.sysmanagement_shared_server_groups tg
WHERE is_system_object = 0
AND (tg.name = @server_group_name OR @server_group_name = ”)
UNION ALL
SELECT cg.parent_id, cg.server_group_id, cg.name
FROM msdb.dbo.sysmanagement_shared_server_groups cg
INNER JOIN ServerGroups pg ON cg.parent_id = pg.server_group_id
)
SELECT s.server_name, sg.name AS GroupName
FROM [msdb].[dbo].[sysmanagement_shared_registered_servers_internal] s
INNER JOIN ServerGroups SG ON s.server_group_id = sg.server_group_id
)
GO
–Update the views which are used in the policy reports
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_ServerGroups]’))
DROP VIEW [policy].[v_ServerGroups]
GO
CREATE VIEW policy.v_ServerGroups AS
WITH ServerGroups(parent_id, server_group_id, GroupName, GroupLevel, Sort, GroupValue)
AS
(SELECT parent_id
, server_group_id
, CAST(‘ALL’ AS varchar(500))
, 1 AS GroupLevel
, CAST(‘ALL’ AS varchar(500)) AS Sort
, CAST(” AS varchar(255)) AS GroupValue
FROM msdb.dbo.sysmanagement_shared_server_groups tg
WHERE server_type = 0 AND parent_id IS NULL
UNION ALL
SELECT cg.parent_id
, cg.server_group_id
, CAST(REPLICATE(‘ ‘, GroupLevel) + cg.name AS varchar(500))
, GroupLevel + 1
, CAST(Sort + ‘ | ‘ + cg.name AS varchar(500)) AS Sort
, CAST(name AS varchar(255)) AS GroupValue
FROM msdb.dbo.sysmanagement_shared_server_groups cg
INNER JOIN ServerGroups pg ON cg.parent_id = pg.server_group_id)
SELECT parent_id, server_group_id, GroupName, GroupLevel, Sort, GroupValue
FROM ServerGroups
GO
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_PolicyHistory]’))
DROP VIEW [policy].[v_PolicyHistory]
GO
CREATE VIEW [policy].[v_PolicyHistory]
AS
–The policy.v_PolicyHistory view will return all results
–and identify the policy evaluation result AS PASS, FAIL, or
–ERROR. The ERROR result indicates that the policy was not able
–to evaluate against an object.
SELECT PH.PolicyHistoryID
, PH.EvaluatedServer
, PH.EvaluationDateTime
, PH.EvaluatedPolicy
, PH.PolicyResult
, PH.ExceptionMessage
, PH.ResultDetail
, PH.EvaluatedObject
, PH.policy_id
, PH.CategoryName
, PH.MonthYear
FROM policy.PolicyHistoryDetail PH
INNER JOIN msdb.dbo.syspolicy_policies AS p ON p.name = PH.EvaluatedPolicy
–INNER JOIN msdb.dbo.syspolicy_policy_categories AS c ON p.policy_category_id = c.policy_category_id
AND PH.EvaluatedPolicy NOT IN (SELECT spp.name
FROM msdb.dbo.syspolicy_policies spp
INNER JOIN msdb.dbo.syspolicy_policy_categories spc ON spp.policy_category_id = spc.policy_category_id
WHERE spc.name = ‘Disabled’)
GO
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_PolicyHistory_Rank]’))
DROP VIEW policy.v_PolicyHistory_Rank
GO
CREATE VIEW policy.v_PolicyHistory_Rank
AS
SELECT PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluatedObject
, PolicyResult
, ResultDetail
, ExceptionMessage
, policy_id
, CategoryName
, MonthYear
, DENSE_RANK() OVER (
PARTITION BY EvaluatedPolicy, EvaluatedServer, EvaluatedObject
ORDER BY EvaluationDateTime DESC) AS EvaluationOrderDesc
FROM policy.v_PolicyHistory VPH
GO
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_PolicyHistory_LastEvaluation]’))
DROP VIEW policy.v_PolicyHistory_LastEvaluation
GO
CREATE VIEW policy.v_PolicyHistory_LastEvaluation
AS
–The policy.v_PolicyHistory_LastEvaluation view will the last result for any given policy evaluated against an object.
–This view requires the v_PolicyHistory view exist.
SELECT PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluatedObject
, PolicyResult
, ResultDetail
, ExceptionMessage
, policy_id
, CategoryName
, MonthYear
, EvaluationOrderDesc
FROM policy.v_PolicyHistory_Rank VPH
WHERE EvaluationOrderDesc = 1
AND NOT EXISTS(
SELECT *
FROM policy.PolicyHistoryDetail PH
WHERE PH.EvaluatedPolicy = VPH.EvaluatedPolicy
AND PH.EvaluatedServer = VPH.EvaluatedServer
AND PH.EvaluationDateTime > VPH.EvaluationDateTime)
GO
–Create a view to return all errors.
–Errors will be returned from the table EvaluationErrorHistory and the errors in the PolicyHistory table.
–Drop the view if it exists.
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_EvaluationErrorHistory]’))
DROP VIEW policy.v_EvaluationErrorHistory
GO
CREATE VIEW policy.v_EvaluationErrorHistory
AS
SELECT EEH.ErrorHistoryID
, EEH.EvaluatedServer
, EEH.EvaluationDateTime
, EEH.EvaluatedPolicy
, CASE WHEN CHARINDEX(‘\’, EEH.EvaluatedServer) > 0
THEN RIGHT(EEH.EvaluatedServer, CHARINDEX(‘\’, REVERSE(EEH.EvaluatedServer)) – 1)
ELSE EEH.EvaluatedServer
END
AS EvaluatedObject
, EEH.EvaluationResults
, p.policy_id
, c.name AS CategoryName
, DATENAME(month, EvaluationDateTime) + ‘ ‘ + datename(year, EvaluationDateTime) AS MonthYear
, ‘ERROR’ AS PolicyResult
FROM policy.EvaluationErrorHistory AS EEH
INNER JOIN msdb.dbo.syspolicy_policies AS p ON p.name = EEH.EvaluatedPolicy
INNER JOIN msdb.dbo.syspolicy_policy_categories AS c ON p.policy_category_id = c.policy_category_id
UNION ALL
SELECT PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, CASE WHEN EvaluatedObject != ‘No Targets Found’
THEN RIGHT(EvaluatedObject, CHARINDEX(‘\’, REVERSE(EvaluatedObject)) – 1)
ELSE EvaluatedObject
END
AS EvaluatedObject
, ExceptionMessage
, policy_id
, CategoryName
, MonthYear
, PolicyResult
FROM policy.v_PolicyHistory_LastEvaluation
WHERE PolicyResult = ‘ERROR’
GO
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[policy].[v_EvaluationErrorHistory_LastEvaluation]’))
DROP VIEW policy.v_EvaluationErrorHistory_LastEvaluation
GO
CREATE VIEW policy.v_EvaluationErrorHistory_LastEvaluation
AS
SELECT ErrorHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, Policy_ID
, EvaluatedObject
, EvaluationResults
, CategoryName
, MonthYear
, PolicyResult
, DENSE_RANK() OVER (
PARTITION BY EvaluatedServer, EvaluatedPolicy
ORDER BY EvaluationDateTime DESC)AS EvaluationOrderDesc
FROM policy.v_EvaluationErrorHistory EEH
WHERE NOT EXISTS (
SELECT *
FROM policy.PolicyHistoryDetail PH
WHERE PH.EvaluatedPolicy = EEH.EvaluatedPolicy
AND PH.EvaluatedServer = EEH.EvaluatedServer
AND PH.EvaluationDateTime > EEH.EvaluationDateTime)
GO
–Update the procedure epm_LoadPolicyHistoryDetail will load the details from the XML documents in PolicyHistory to the PolicyHistoryDetails table.
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[policy].[epm_LoadPolicyHistoryDetail]’) AND type in (N’P’, N’PC’))
DROP PROCEDURE [policy].[epm_LoadPolicyHistoryDetail]
GO
CREATE PROCEDURE policy.epm_LoadPolicyHistoryDetail @PolicyCategoryFilter VARCHAR(255)
AS
SET NOCOUNT ON;
IF @PolicyCategoryFilter = ”
SET @PolicyCategoryFilter = NULL
DECLARE @sqlcmd VARCHAR(8000), @Text NVARCHAR(255), @Remain int
SELECT @Text = CONVERT(varchar, GETDATE(), 9) + ‘ – Starting data integration for ‘ + CASE WHEN @PolicyCategoryFilter IS NULL THEN ‘ALL categories’ ELSE ‘Category ‘ + @PolicyCategoryFilter END
RAISERROR (@Text, 10, 1) WITH NOWAIT;
–Insert the evaluation results.
SELECT @sqlcmd = ‘;WITH XMLNAMESPACES (”http://schemas.microsoft.com/sqlserver/DMF/2007/08” AS DMF)
,cteEval AS (SELECT PH.PolicyHistoryID
, PH.EvaluatedServer
, PH.EvaluationDateTime
, PH.EvaluatedPolicy
, Res.Expr.value(”(../DMF:TargetQueryExpression)[1]”, ”nvarchar(150)”) AS EvaluatedObject
, (CASE WHEN Res.Expr.value(”(../DMF:Result)[1]”, ”nvarchar(150)”) = ”FALSE” AND Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) = ””
THEN ”FAIL”
WHEN Res.Expr.value(”(../DMF:Result)[1]”, ”nvarchar(150)”)= ”FALSE” AND Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) <> ””
THEN ”ERROR”
ELSE ”PASS”
END) AS PolicyResult
, Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) AS ExceptionMessage
, CAST(Expr.value(”(../DMF:ResultDetail)[1]”, ”nvarchar(max)”)AS XML) AS ResultDetail
, p.policy_id
, c.name AS CategoryName
, datename(month, EvaluationDateTime) + ” ” + datename(year, EvaluationDateTime) AS MonthYear
, ”PowerShell EPM Framework” AS PolicyHistorySource
, DENSE_RANK() OVER (PARTITION BY Res.Expr.value(”(../DMF:TargetQueryExpression)[1]”, ”nvarchar(150)”) ORDER BY Expr) AS [TopRank]
FROM policy.PolicyHistory AS PH
INNER JOIN msdb.dbo.syspolicy_policies AS p ON p.name = PH.EvaluatedPolicy
INNER JOIN msdb.dbo.syspolicy_policy_categories AS c ON p.policy_category_id = c.policy_category_id
CROSS APPLY EvaluationResults.nodes(”declare default element namespace “http://schemas.microsoft.com/sqlserver/DMF/2007/08”;
//TargetQueryExpression”
) AS Res(Expr)
WHERE NOT EXISTS (SELECT DISTINCT PHD.PolicyHistoryID FROM policy.PolicyHistoryDetail PHD WITH(NOLOCK) WHERE PHD.PolicyHistoryID = PH.PolicyHistoryID AND PHD.ResultDetail IS NOT NULL)
‘ + CASE WHEN @PolicyCategoryFilter IS NULL THEN ” ELSE ‘AND c.name = ”’ + @PolicyCategoryFilter + ”” END + ‘
AND EvaluationResults.exist(”declare namespace DMF=”http://schemas.microsoft.com/sqlserver/DMF/2007/08″;
//DMF:EvaluationDetail”) = 1)
INSERT INTO policy.PolicyHistoryDetail (
PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluatedObject
, PolicyResult
, ExceptionMessage
, ResultDetail
, policy_id
, CategoryName
, MonthYear
, PolicyHistorySource
)
SELECT PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluatedObject
, PolicyResult
, ExceptionMessage
, ResultDetail
, policy_id
, CategoryName
, MonthYear
, PolicyHistorySource
FROM cteEval
WHERE cteEval.[TopRank] = 1′; — Remove duplicates
EXEC (@sqlcmd);
SELECT @Text = CONVERT(NVARCHAR, GETDATE(), 9) + ‘ |- ‘ + CONVERT(NVARCHAR, @@ROWCOUNT) + ‘ rows inserted…’
RAISERROR (@Text, 10, 1) WITH NOWAIT;
SELECT @Text = CONVERT(varchar, GETDATE(), 9) + ‘ – Starting no target data integration’
RAISERROR (@Text, 10, 1) WITH NOWAIT;
–Insert the policies that evaluated with no target
SELECT @sqlcmd = ‘;WITH XMLNAMESPACES (”http://schemas.microsoft.com/sqlserver/DMF/2007/08” AS DMF)
INSERT INTO policy.PolicyHistoryDetail (
PolicyHistoryID
, EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluatedObject
, PolicyResult
, ExceptionMessage
, ResultDetail
, policy_id
, CategoryName
, MonthYear
, PolicyHistorySource
)
SELECT PH.PolicyHistoryID
, PH.EvaluatedServer
, PH.EvaluationDateTime
, PH.EvaluatedPolicy
, ”No Targets Found” AS EvaluatedObject
, (CASE WHEN Res.Expr.value(”(../DMF:Result)[1]”, ”nvarchar(150)”)= ”FALSE” AND Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) = ””
THEN ”FAIL”
WHEN Res.Expr.value(”(../DMF:Result)[1]”, ”nvarchar(150)”)= ”FALSE” AND Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”)<> ””
THEN ”ERROR”
ELSE ”PASS”
END) AS PolicyResult
, Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) AS ExceptionMessage
, NULL AS ResultDetail
, p.policy_id
, c.name AS CategoryName
, datename(month, EvaluationDateTime) + ” ” + datename(year, EvaluationDateTime) AS MonthYear
, ”PowerShell EPM Framework”
FROM policy.PolicyHistory AS PH
INNER JOIN msdb.dbo.syspolicy_policies AS p ON p.name = PH.EvaluatedPolicy
INNER JOIN msdb.dbo.syspolicy_policy_categories AS c ON p.policy_category_id = c.policy_category_id
CROSS APPLY EvaluationResults.nodes(”declare default element namespace “http://schemas.microsoft.com/sqlserver/DMF/2007/08”;
//DMF:ServerInstance”
) AS Res(Expr)
WHERE NOT EXISTS (SELECT DISTINCT PHD.PolicyHistoryID FROM policy.PolicyHistoryDetail PHD WITH(NOLOCK) WHERE PHD.PolicyHistoryID = PH.PolicyHistoryID AND PHD.ResultDetail IS NULL)
‘ + CASE WHEN @PolicyCategoryFilter IS NULL THEN ” ELSE ‘AND c.name = ”’ + @PolicyCategoryFilter + ”” END + ‘
AND EvaluationResults.exist(”declare namespace DMF=”http://schemas.microsoft.com/sqlserver/DMF/2007/08″;
//DMF:EvaluationDetail”) = 0
ORDER BY DENSE_RANK() OVER (ORDER BY Expr);’ — Remove duplicates
EXEC (@sqlcmd);
SELECT @Text = CONVERT(NVARCHAR, GETDATE(), 9) + ‘ |- ‘ + CONVERT(NVARCHAR, @@ROWCOUNT) + ‘ rows inserted…’
RAISERROR (@Text, 10, 1) WITH NOWAIT;
SELECT @Text = CONVERT(varchar, GETDATE(), 9) + ‘ – Starting errors data integration’
RAISERROR (@Text, 10, 1) WITH NOWAIT;
–Insert the error records
SELECT @sqlcmd = ‘;WITH XMLNAMESPACES (”http://schemas.microsoft.com/sqlserver/DMF/2007/08” AS DMF)
INSERT INTO policy.EvaluationErrorHistory(
EvaluatedServer
, EvaluationDateTime
, EvaluatedPolicy
, EvaluationResults
)
SELECT PH.EvaluatedServer
, PH.EvaluationDateTime
, PH.EvaluatedPolicy
, Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) AS ExceptionMessage
FROM policy.PolicyHistory AS PH
INNER JOIN msdb.dbo.syspolicy_policies AS p ON p.name = PH.EvaluatedPolicy
INNER JOIN msdb.dbo.syspolicy_policy_categories AS c ON p.policy_category_id = c.policy_category_id
CROSS APPLY EvaluationResults.nodes(”declare default element namespace “http://schemas.microsoft.com/sqlserver/DMF/2007/08”;
//DMF:ServerInstance”
) AS Res(Expr)
WHERE PH.PolicyHistoryID NOT IN (SELECT DISTINCT PH.PolicyHistoryID FROM policy.EvaluationErrorHistory AS PHD WITH(NOLOCK) INNER JOIN policy.PolicyHistory AS PH WITH(NOLOCK) ON PH.EvaluatedServer = PHD.EvaluatedServer AND PH.EvaluationDateTime = PHD.EvaluationDateTime AND PH.EvaluatedPolicy = PHD.EvaluatedPolicy)
‘ + CASE WHEN @PolicyCategoryFilter IS NULL THEN ” ELSE ‘AND c.name = ”’ + @PolicyCategoryFilter + ”” END + ‘
AND Expr.value(”(../DMF:Exception)[1]”, ”nvarchar(max)”) <> ””
–AND Res.Expr.value(”(../DMF:Result)[1]”, ”nvarchar(150)”) = ”FALSE”
ORDER BY DENSE_RANK() OVER (ORDER BY Expr);’ — Remove duplicates
EXEC (@sqlcmd);
SELECT @Text = CONVERT(NVARCHAR, GETDATE(), 9) + ‘ |- ‘ + CONVERT(NVARCHAR, @@ROWCOUNT) + ‘ rows inserted…’
RAISERROR (@Text, 10, 1) WITH NOWAIT;
SELECT @Text = CONVERT(varchar, GETDATE(), 9) + ‘ – Finished data integration for ‘ + CASE WHEN @PolicyCategoryFilter IS NULL THEN ‘ALL categories’ ELSE ‘Category ‘ + @PolicyCategoryFilter END
RAISERROR (@Text, 10, 1) WITH NOWAIT;
GO
USE $(ManagementDatabase)
GO
EXEC policy.epm_LoadPolicyHistoryDetail NULL
GO
USE $(ManagementDatabase)
GO
IF (SELECT SERVERPROPERTY(‘EditionID’)) IN (1804890536, 1872460670, 610778273, -2117995310) — Supports Enterprise only features
BEGIN
ALTER INDEX [PK_EvaluationErrorHistory] ON [policy].[EvaluationErrorHistory] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE)
ALTER INDEX [PK_PolicyHistoryDetail] ON [policy].[PolicyHistoryDetail] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE)
ALTER INDEX [PK_PolicyHistory] ON [policy].[PolicyHistory] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE)
END;
GO
ExtractConditionResults-PROC
USE [dbDooT]
GO
/ Object: StoredProcedure [dbo].[ExtractConditionResults] Script Date: 10/05/2021 16:11:30 /
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
— Created by Tore Olafsson 07/05/2021 for the SQL Server part fo the dbDooT project
create procedure [dbo].[ExtractConditionResults]
as
SET NOCOUNT ON;
declare @datecondition varchar(50)
set @datecondition = FORMAT (getdate(), ‘yyyy-MM-dd’)
— Eliminate any results which have already been uploaded
if not exists (Select EvaluatedPolicy from [dbDooT].[policy].[PolicyConditionResults] where EvaluationDateTime = (Select max(EvaluationDateTime) from [dbDooT].[policy].[PolicyHistoryDetail])
and EvaluatedServer in (select EvaluatedServer from [dbDooT].[policy].[PolicyHistoryDetail]))
BEGIN
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime > =’2021-05-06′
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
–To pick up values within Grouped PBM Condition Facets
insert into [dbDooT].[policy].[PolicyConditionResults]
SELECT DISTINCT e.EvaluationDateTime, e.EvaluatedPolicy, e.EvaluatedServer, e.EvaluatedObject,
X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) as Name,
X.Y.value(‘(ResultValue)[1]’, ‘VARCHAR(256)’) as ResultValue,
e.PolicyHistoryID, e.CategoryName
FROM [dbDooT].[policy].[PolicyHistoryDetail] e
OUTER APPLY e.ResultDetail.nodes(‘Operator/Group/Operator/Operator/Attribute’) as X(Y)
where X.Y.value(‘(Name)[1]’, ‘VARCHAR(256)’) is not null
and e.EvaluationDateTime >= @datecondition
END
GO
EPM_EnterpriseEvaluation_4.ps1
Evaluate specific Policies against a Server List
Uses the Invoke-PolicyEvaluation Cmdlet
param([string]$ConfigurationGroup=$(Throw "Parameter missing: -ConfigurationGroup ConfigGroup"),
[string]$PolicyCategoryFilter=$(Throw “Parameter missing: -PolicyCategoryFilter Category"),
[string]$EvalMode=$(Throw “Parameter missing: -EvalMode EvalMode”))
Parameter -ConfigurationGroup specifies the
Central Management Server group to evaluate
Parameter -PolicyCategoryFilter specifies the
category of policies to evaluate
Parameter -EvalMode accepts “Check” to report policy
results, “Configure” to reconfigure any violations
Declare variables to define the central warehouse
in which to write the output, store the policies
$CentralManagementServer = “SYBENG01”
$HistoryDatabase = “dbDooT”
Define the location to write the results of the policy evaluation
$ResultDir = “D:\Shared\EPM\EPM-Results\”
End of variables
Function to insert policy evaluation results into SQL Server – table policy.PolicyHistory
function PolicyHistoryInsert($sqlServerVariable, $sqlDatabaseVariable, $EvaluatedServer, $EvaluatedPolicy, $EvaluationResults)
{
&{
$sqlQueryText = “INSERT INTO policy.PolicyHistory (EvaluatedServer, EvaluatedPolicy, EvaluationResults) VALUES(N’$EvaluatedServer’, N’$EvaluatedPolicy’, N’$EvaluationResults’)”
Invoke-Sqlcmd -ServerInstance $sqlServerVariable -Database $sqlDatabaseVariable -Query $sqlQueryText -ErrorAction Stop
}
trap
{
$ExceptionText = $_.Exception.Message -replace “‘”, “”
}
}
Function to insert policy evaluation errors into SQL Server – table policy.EvaluationErrorHistory
function PolicyErrorInsert($sqlServerVariable, $sqlDatabaseVariable, $EvaluatedServer, $EvaluatedPolicy, $EvaluationResultsEscape)
{
&{
$sqlQueryText = “INSERT INTO policy.EvaluationErrorHistory (EvaluatedServer, EvaluatedPolicy, EvaluationResults) VALUES(N’$EvaluatedServer’, N’$EvaluatedPolicy’, N’$EvaluationResultsEscape’)”
Invoke-Sqlcmd -ServerInstance $sqlServerVariable -Database $sqlDatabaseVariable -Query $sqlQueryText -ErrorAction Stop
}
trap
{
$ExceptionText = $_.Exception.Message -replace “‘”, “”
}
}
Function to delete files from this policy only
function PolicyFileDelete($File)
{
# Delete evaluation files in the directory.
Remove-Item -Path $File
# ugly but moves on…
trap
{
continue;
}
}
Connection to the policy store
$conn = new-object Microsoft.SQlServer.Management.Sdk.Sfc.SqlStoreConnection(“server=$CentralManagementServer;Trusted_Connection=true”);
$PolicyStore = new-object Microsoft.SqlServer.Management.DMF.PolicyStore($conn);
Create recordset of servers to evaluate
$sconn = new-object System.Data.SqlClient.SqlConnection(“server=$CentralManagementServer;Trusted_Connection=true”);
$q = “SELECT DISTINCT server_name FROM $HistoryDatabase.[policy].pfn_ServerGroupInstances;”
$sconn.Open()
$cmd = new-object System.Data.SqlClient.SqlCommand ($q, $sconn);
$cmd.CommandTimeout = 0;
$dr = $cmd.ExecuteReader();
Loop through the servers and then loop through
the policies. For each server and policy,
call cmdlet to evaluate policy on server and delete xml file afterwards
while ($dr.Read()) {
$ServerName = $dr.GetValue(0);
foreach ($Policy in $PolicyStore.Policies)
{
if (($Policy.PolicyCategory -eq $PolicyCategoryFilter)-or ($PolicyCategoryFilter -eq “”))
{
&{
$OutputFile = $ResultDir + (“{0}{1}.xml” -f (Encode-SqlName $ServerName ), ($Policy.Name)); Invoke-PolicyEvaluation -Policy $Policy -TargetServerName $ServerName -AdHocPolicyEvaluationMode $EvalMode -OutputXML > $OutputFile; $PolicyResult = Get-Content $OutputFile -encoding UTF8; $PolicyResult = $PolicyResult -replace “‘”, “” PolicyHistoryInsert $CentralManagementServer $HistoryDatabase $ServerName $Policy.Name $PolicyResult; $File = $ResultDir + (“{0}.xml” -f ($Policy.Name));
PolicyFileDelete $File;
}
trap [Exception]
{
$File = $ResultDir + (“{0}.xml” -f ($Policy.Name)); PolicyFileDelete $File; $ExceptionText = $.Exception.Message -replace “‘”, “”
$ExceptionMessage = $_.Exception.GetType().FullName + “, ” + $ExceptionText
PolicyErrorInsert $CentralManagementServer $HistoryDatabase $ServerName $Policy.Name $ExceptionMessage;
continue;
}
}
}
}
$dr.Close()
$sconn.Close()
Shred the XML results to PolicyHistoryDetails
Invoke-Sqlcmd -ServerInstance $CentralManagementServer -Database $HistoryDatabase -Query “EXEC policy.epm_LoadPolicyHistoryDetail `$(PolicyCategory)” -Variable “PolicyCategory=’${PolicyCategoryFilter}'” -QueryTimeout 65535 -Verbose -ErrorAction Stop