This article discusses a simple solution of how to monitor SQL service availability across multiple servers and reporting. To build this I’ll use SQL Server with simple PowerShell script and cmdlets which generate JSON data and displays results in HTML

本文讨论了一个简单的解决方案,该方案如何监视跨多个服务器SQL服务可用性和报告。 为此,我将使用带有简单PowerShell脚本和cmdletSQL Server,这些脚本和cmdlet会生成JSON数据并以HTML显示结果

文章重点 ( Article highlights )

  • Defines the objective of JSON 定义JSON的目标
  • Explains the PoSH JSON cmdllets internals and other details on its usage 解释PoSH JSON cmdllets内部结构及其用法的其他详细信息
  • Proactive Monitoring of Service(s) over multiple servers – Covers fundamentals of how to Monitor SQL service(s). This sample code can be implemented to monitor any services on a Windows environment 主动监视多个服务器上的服务–涵盖了如何监视SQL服务的基础知识。 可以实施此示例代码来监视Windows环境上的任何服务
  • Automated Process – Easy to implement If you don’t have a monitoring tool 自动化流程–易于实施如果您没有监控工具
  • Easier customization of services list and input servers list 轻松定制服务列表和输入服务器列表
  • Seamless Integration of PowerShell and SQL using SQL 2016 JSON constructs 使用SQL 2016 JSON构造将PowerShell和SQL无缝集成
  • HTML Report – shows how to do effective reporting using XML parsing and Database Mail HTML报告–显示如何使用XML解析和数据库邮件进行有效的报告
  • Summary of data 数据汇总

使用的技术 ( Technologies used )

  • SQL 2016 JSON Constructs – OPENROWSET and OPENJSON for JSON data manipulation and transformation into relational data SQL 2016 JSON构造– OPENROWSET和OPENJSON用于JSON数据操作并将其转换为关系数据
  • PowerShell Cmdlets – ConvertTo-JSON for Data export, ConvertFrom-JSON for Data import PowerShell Cmdlet –用于数据导出的ConvertTo-JSON,用于数据导入的ConvertFrom-JSON
  • XML Parsing for Prepare HTML tags 用于准备HTML标签的XML解析
  • SQL Database Mail for the Email exchange 用于电子邮件交换SQL数据库邮件

An integration of JSON in the relational world provides a robust platform for various automations using PowerShell automation framework. There are several JSON constructs available in SQL 2016 to manipulate and transform JSON data into relation data. The relational architecture in support of JSON provides several benefits in the non-relational world from the point of Migration and deployment. It is flexible because of simple syntax and lesser overhead to maintain and manage the JSON data. Parsing of relational data using XML gives the flexibility to manipulate huge data which will ease out the functioning of reporting

JSON在关系世界中的集成为使用PowerShell自动化框架的各种自动化提供了一个强大的平台。 SQL 2016中提供了几种JSON构造,用于处理JSON数据并将其转换为关系数据。 从迁移和部署的角度来看,支持JSON的关系体系结构在非关系世界中提供了许多好处。 由于语法简单且维护和管理JSON数据的开销较小,因此它很灵活。 使用XML解析关系数据可灵活地处理海量数据,这将简化报告的功能

技术概述 ( Technical overview )

This article will provide an overview of the following technical implementations

本文将概述以下技术实现

  • Various methods and techniques implemented to find the windows service  实施各种方法和技术来查找Windows服务
  • Details about the purpose and benefits of using JSON 有关使用JSON的目的和好处的详细信息
  • Pre-requisites and installation of related Powershelll components 先决条件和相关Powershelll组件的安装
  • cmdlets under the respective library are listed 列出了各个库下的cmdlet
  • The convertTo-JSON and convertFROM-JSON will explained with an example along with 将通过示例解释convertTo-JSON和convertFROM-JSON以及
  • JSON data representation in various tabular formats 各种表格格式的JSON数据表示
  • Finally, the constructs used to manipulate the JSON string will be illustrated with an example 最后,将通过一个示例来说明用于操作JSON字符串的结构。
  • Transformation of JSON data using SQL constructs 使用SQL构造转换JSON数据

Let’s discuss the internals of JSON and cmdlets which are used to build the PowerShell script for generating the JSON data

让我们讨论JSON和cmdlet的内部原理,它们用于构建用于生成JSON数据的PowerShell脚本

JSON(JavaScript对象表示法) ( JSON (JavaScript Object Notation) )

JSON is an Open standard, lightweight data exchange based on a subset of the JavaScript Programming Language. It is easy for humans to parse and generate value out of each attribute. XML used to be a preferred choice for data exchange over the internet and it enjoyed the top spot for a long time but the gradual tendency of people to shift towards JSON due to its simple structure.

JSON是基于JavaScript编程语言的子集的开放标准,轻量级数据交换。 人类很容易解析并从每个属性中产生价值。 XML过去一直是Internet上数据交换的首选,并且长期以来一直处于头把交椅,但是由于其结构简单,人们逐渐倾向于JSON。

PowerShell中的JSON ( JSON in PowerShell )

Microsoft provides a framework and useful cmdlets to work with JSON. The ConvertTo-Json and ConvertFrom-Json cmdlets play a vital role in data transformation. These cmdlets allow working with APIs or classes and returns or accept JSON as an input.

Microsoft提供了使用JSON的框架和有用的cmdlet。 ConvertTo-Json和ConvertFrom-Json cmdlet在数据转换中起着至关重要的作用。 这些cmdlet允许使用API​​或类,并返回或接受JSON作为输入。

转换为杰森 ( ConvertTo-Json  )

The ConvertTo-Json cmdlet converts any object to a string in JavaScript Object Notation (JSON) format. The properties are converted to field names, the field values are converted to property values, and the methods are removed.

ConvertTo-Json cmdlet可以将任何对象转换为JavaScript Object Notation(JSON)格式的字符串。 将属性转换为字段名称,将字段值转换为属性值,然后删除方法。

You can then use the ConvertFrom-Json cmdlet to convert a JSON-formatted string to a JSON object, which is easily managed in Windows PowerShell.

然后,您可以使用ConvertFrom-Json cmdlet将JSON格式的字符串转换为JSON对象,可以在Windows PowerShell中轻松地对其进行管理。

ConvertFrom-JSON ( ConvertFrom-JSON )

The ConvertFrom-Json cmdlet converts a JavaScript Object Notation (JSON) formatted string to a custom PSCustomObjectobject that has a property for each field in the JSON string.  JSON is commonly used by websites to provide a textual representation of objects.

ConvertFrom-Json cmdlet将JavaScript对象表示法(JSON)格式的字符串转换为自定义PSCustomObject对象,该对象具有JSON字符串中每个字段的属性。 网站通常使用JSON来提供对象的文本表示。

Pre-requisite

前提条件

  • Minimum shell version -> PowerShell 3.0 最低Shell版本-> PowerShell 3.0
  • SQL 2016 for Data transformation SQL 2016用于数据转换

Powershell 3.0 is integrated with Windows 8 released on 9/12/2011. This bundle in houses two new functions ConvertFrom-Json and ConvertTo-Json to support JSON.The ConvertFrom-Json is included in the module Microsoft.PowerShell.Utility, make sure that the module is loaded by doing Import-Module Microsoft.PowerShell.Utility before you use ConvertTo-Json. These are the default modules will be automatically loaded with your profile.

Powershell 3.0与2011年9月12日发布的Windows 8集成在一起。 该捆绑软件包含两个新功能ConvertFrom-Json和ConvertTo-Json以支持JSON.ConvertFrom-Json包含在模块Microsoft.PowerShell.Utility中,请通过执行Import-Module Microsoft.PowerShell.Utility确保模块已加载在使用ConvertTo-Json之前。 这些是默认模块,它们会自动随您的配置文件一起加载。

如何列出和验证模块监视器 ( How to List and verify the Modules monitor )

The next question would be how do I retrieve the available commands from a module?. There are instances that modules are not loaded due to the profile problem. The below commands ensures that the cmdlets are loaded and it’s available for use.

下一个问题是如何从模块中检索可用的命令? 在某些情况下,由于配置文件问题而导致模块未加载。 以下命令确保cmdlet已加载并且可以使用。


PS P:\> Get-Module -ListAvailablePS P:\>Get-Module Microsoft.PowerShell.Utility -ListAvailable | % { $_.ExportedCommands.Values }

The below sample code retrieves the details of listed services from the remote server(s).

下面的示例代码从远程服务器检索列出的服务的详细信息。


<#.SYNOPSIS       Name :  Service Report (Get-ServiceJSON.ps1)Description : Get disk space usage information from remote server(s) with WMI and ouput JSON fileAuthor : Prashanth Jayaram* Select list of servers from a text file* Get remote Servers information with WMI and Powershell* Service  (Servername,Name,startmode,state,serviceaccount,displayname + JSON Output) .INPUTInput Server text fileService list.OUTPUTSJSON output, console .NOTESVersion:        1.0Author:         Prashanth JayaramCreation Date:  2017-03-08Purpose/Change: Initial script developmentUse the Get-Content cmdlet with the Raw parameter to read JSON file.EXAMPLE.\Get-ServiceJSON.ps1 -ServerList "\\hq6021\c$\server.txt" -includeService "VM","Dhcp","SQL" -JSONoutputFile "e:\CU2\ServericeReport.JSON"#>#########################################################################################param ([Parameter(Mandatory=$true)][string]$ServerList,[Parameter(Mandatory=$true)][string[]]$includeService,[Parameter(Mandatory=$true)][string]$JSONoutputFile)# Check if the output file CSV exist, if exists then delete it.if (test-path $JSONoutputFile ) { rm $JSONoutputFile }  #Custom object to maintain the order of the output columns$props=@()Foreach($ServerName in (Get-Content $ServerList))
{
$service = Get-WmiObject Win32_Service -ComputerName $servername
if ($Service -ne $NULL)  {
foreach ($item in $service)  {  #$item.DisplayName  Foreach($include in $includeService)   {                         #write-host $inlcude                                      if(($item.name).Contains($include) -eq $TRUE)  { $props += [pscustomobject]@{Servername = $servernamename =  $item.nameStatus = $item.Status startmode = $item.startmode state = $item.stateserviceaccount=$item.startnameDisplayName =$item.displayname}}  }  }  }
}  #$props | Format-Table Servername,Name,startmode,state,serviceaccount,displayname  -AutoSize#convert the output to JSON$json=$props | Select-Object Servername,Name,startmode,state,serviceaccount,displayname  |ConvertTo-Json#write the output to file$json |Out-File $JSONoutputFile#invoke to process to open JSON fileinvoke-item $JSONoutputFile

Reading the content of a file in PowerShell is very easy. Use the Get-Content cmdlet with the raw parameter to read the content of JSON file.

在PowerShell中读取文件的内容非常容易。 使用带有raw参数的Get-Content cmdlet读取JSON文件的内容。


$json=Get-Content -Raw -Path E:\cu2\ServericeReport.JSON | ConvertFrom-Json
$json | select-object @{Name="servername";Expression={$_.servername.value}},name,startmode,state,serviceaccount,displayname| ft -AutoSize 

JSON的关系数据表示 ( Relational data presentation for JSON )

Let’s discuss the JSON data representation in a tabular format by importing the JSON file in SQL Server. The OPENROWSET(BULK) is Table Valued function to read data from JSON file. The SQL 2016 contains various JSON constructs for data manipulation and relational data transformation.

让我们通过在SQL Server中导入JSON文件来讨论表格格式的JSON数据表示形式。 OPENROWSET(BULK)是表值函数,用于从JSON文件读取数据。 SQL 2016包含用于数据操作和关系数据转换的各种JSON构造。

  • OPENJSON(BULK) – The TVF(Table Valued Function) reads and content of JSON file and return the value via BulkColumn. The return value is either stored in a variable or table. OPENJSON(BULK)– TVF(表值函数)读取JSON文件并显示其内容,并通过BulkColumn返回值。 返回值存储在变量或表中。

This section details the use of OPENROWSET(BULK) and OPENJSON(Bulkcolumn).The OPENROWSET read text value from a file and return it as Bulkcolumn. The Bulkcolumn is then passed to OPENJSON TVF. The function will iterate over the array values to return required values of each attribute.

本节详细介绍OPENROWSET(BULK)和OPENJSON(Bulkcolumn)的用法。OPENROWSET从文件中读取文本值,并将其作为Bulkcolumn返回。 然后,将Bulkcolumn传递给OPENJSON TVF。 该函数将遍历数组值以返回每个属性的必需值。

Let’s execute the SQL to import the JSON data. The JSON file is saved in Unicode format hence have used SINGLE_NCLOB in the SQL. You can also make use of other bulk loading options such SINGLE_CLOB, SINGLE_BLOB depending on the type of the data stored in a file. The below SQL is an effort to define the use of inline JSON data processing.

让我们执行SQL来导入JSON数据。 JSON文件以Unicode格式保存,因此已在SQL中使用SINGLE_NCLOB。 您还可以根据文件中存储的数据类型使用其他批量加载选项,例如SINGLE_CLOB,SINGLE_BLOB。 下面SQL旨在定义内联JSON数据处理的使用。


SELECT t2.value Servername,t.name,t.startmode,t.state, t.serviceaccount,t.DisplayName   FROM
OPENROWSET(BULK N'\\hqsqrt05\e$\cu2\Serverice.JSON', SINGLE_NCLOB) AS JSONCROSS APPLY OPENJSON(BulkColumn)WITH(name nvarchar(40),   startmode NVARCHAR(20),state NVARCHAR(20),serviceaccount NVARCHAR(60),DisplayName NVARCHAR(60),Servername NVARCHAR(MAX) as JSON) AS tCROSS APPLY OPENJSON(Servername)
WITH(value nvarchar(100)) t2

内置JSON构造用于数据处理 (In-Built JSON constructs for data processing)

Processing is made much easier by using the available JSON constructs on referring JSON paths. In this case, the dollar sign ($) references entire JSON object in the input text for processing. The OPENJSON is a table-value function that parses JSON text and returns objects and properties in JSON as rows and columns. The OPENJSON function and with clause lets to define an explicit schema.

通过在引用JSON路径上使用可用的JSON构造,处理变得更加容易。 在这种情况下,美元符号($)引用输入文本中的整个JSON对象进行处理。 OPENJSON是一个表值函数,它解析JSON文本并以行和列的形式返回JSON中的对象和属性。 OPENJSON函数和with子句可用于定义显式架构。

This is another way of processing the JSON text using JSON path references.

这是使用JSON路径引用处理JSON文本的另一种方法。


SELECT t.* FROM
OPENROWSET(BULK N'\\hqsqrt05\e$\cu2\Serverice.JSON', SINGLE_NCLOB) AS JSONCROSS APPLY OPENJSON(BulkColumn)WITH(Servername NVARCHAR(20) '$.Servername.value' ,name nvarchar(40),   startmode NVARCHAR(20),state NVARCHAR(20),serviceaccount NVARCHAR(60),DisplayName NVARCHAR(60)
) AS t

报告中 (Reporting)

Using the FOR XML PATH the casting is done to the string in the result set but not on each column attributes this itself is a great improvement when you deal with huge data. The use of RAW clause which adds the new table row string at the beginning of each record and the ELEMENTS and the [td] column name help to set the cells tags in the HTML table otherwise, each tag would contain the column name. As you can see, using FOR XML PATH can improve the way we write our reports.

使用FOR XML PATH,可以对结果集中的字符串进行强制转换,但不能对每个列属性进行强制转换,这在处理海量数据时本身就是一个很大的改进。 使用RAW子句在每个记录的开头添加新的表行字符串,以及ELEMENTS和[td]列名有助于在HTML表中设置单元格标记,否则,每个标记将包含列名。 如您所见,使用FOR XML PATH可以改善我们编写报告的方式。

结论 ( Conclusion )

One of the important system parameters to be measured to increase the availability of the application is discussed in this article. The process, described in this article can be implemented by anyone who monitors large and complex environments across multiple servers as the script has the provision of making customization to the services list and server list.

本文讨论了要提高应用程序可用性的重要系统参数之一。 监视跨多个服务器的大型和复杂环境的任何人都可以实现本文描述的过程,因为脚本提供了对服务列表和服务器列表进行自定义的功能。

参考资料 (References)

  • SQL Server 2016: JSON integration SQL Server 2016:JSON整合
  • FOR XML (SQL Server) FOR XML(SQL Server)
  • OPENJSON (Transact-SQL) OPENJSON(Transact-SQL)
  • Configure SQL Server Agent Mail to Use Database Mail 配置SQL Server代理邮件以使用数据库邮件

翻译自: https://www.sqlshack.com/illustration-of-an-example-availability-monitoring-service-using-powershell-and-sql/

使用PowerShell和SQL的示例可用性监视服务的插图相关推荐

  1. PowerShell 导入 SQL Server 的 PS 模块

    接触过UNIX或者Linux 的朋友都知道此类系统有着功能强大.无所不能的壳程序,称之为Shell.微软公司于2006年第四季度正式发布PowerShell,它的出现标志着, 微软公司向服务器领域迈出 ...

  2. 学习PowerShell和SQL Server –简介

    介绍 (Introduction) This article is the first step among many that I hope will help give you a foundat ...

  3. 使用PowerShell模块SQL数据库备份– DBATools

    This article will be first article of series for SQL database backup and restoration using DBAtools, ...

  4. 使用DBATools PowerShell修复SQL Server中的孤立用户

    This article gives an overview of Orphan users and fixing them using DBATools PowerShell. 本文概述了Orpha ...

  5. Flink1.7.2 sql 批处理示例

    Flink1.7.2 sql 批处理示例 源码 https://github.com/opensourceteams/flink-maven-scala 概述 本文为Flink sql Dataset ...

  6. 《PowerShell V3——SQL Server 2012数据库自动化运维权威指南》——2.8 创建数据库...

    本节书摘来自异步社区出版社<PowerShell V3-SQL Server 2012数据库自动化运维权威指南>一书中的第2章,第2.8节,作者:[加拿大]Donabel Santos,更 ...

  7. 《PowerShell V3——SQL Server 2012数据库自动化运维权威指南》——1.5 安装SMO

    本节书摘来自异步社区出版社<PowerShell V3-SQL Server 2012数据库自动化运维权威指南>一书中的第1章,第1.5节,作者:[加拿大]Donabel Santos,更 ...

  8. 《PowerShell V3——SQL Server 2012数据库自动化运维权威指南》——2.19 使用bcp实施批量导出...

    本节书摘来自异步社区出版社<PowerShell V3-SQL Server 2012数据库自动化运维权威指南>一书中的第2章,第2.19节,作者:[加拿大]Donabel Santos, ...

  9. python创建数据库的sql语句_对python插入数据库和生成插入sql的示例讲解

    如下所示: #-*- encoding:utf-8 -*- import csv import sys,os import pymysql def read_csv(filename): ''' 读取 ...

最新文章

  1. 用缓动函数模拟物理动画
  2. 批量ping 查看主机能否ping通,能否ssh上.md,
  3. monkeyrunner自动登录脚本
  4. android 判断fragment类型,Android 判断当前Fragment是否可见(Visible)
  5. VISIO——word中插入visio图片 图片边缘空白裁剪
  6. QQlook--QQ空间密码 相册密码查看工具 国庆版 V2.4
  7. C4D插件X-Particles粒子特效(六)
  8. 计算机网络技术发展四个阶段,计算机网络的发展分哪四个阶段,特点?
  9. WiFi语音智能家居控制系统(一)
  10. 三极管的基础知识(下)①
  11. 大数据可视化课程笔记 6
  12. 处理机和CPU的区别
  13. php开发实例大全pdf百度云盘_你们要的PDF免费转换工具,支持在线编辑PDF。
  14. 计算机键盘时好时坏,机子的CTRL键时好时坏?
  15. 国产充电宝有哪些,国产充电宝哪个牌子的质量好?
  16. 三、docker镜像创建
  17. 十所大学!计算机第二学士学位开始报名!
  18. 前端应该了解的PWA
  19. 用Python打造你的专属情人节贺卡,赶快发给TA浪漫一下吧
  20. 陷阱技术探秘 ──动态汉化Windows技术的分析 (转)

热门文章

  1. xmpp协议详解一:xmpp基本概念
  2. 数据结构:树套树-替罪羊树套权值线段树
  3. DevExpress下拉多选框 CheckComboboxEdit、CheckedListBoxControl
  4. NASA的10条代码编写原则
  5. 微信 小程序组件 焦点切换
  6. [LeetCode] 3Sum Closest
  7. oracle的数据泵导入,导出以及创建用户及删除当前连接用户
  8. React+TS免注册DOM页面dialog弹窗
  9. ★LeetCode(429)——N叉树的层序遍历(JavaScript)
  10. 【Vue2.0】—props 配置(十三)