博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用PowerShell和SQL的示例可用性监视服务的插图
阅读量:2513 次
发布时间:2019-05-11

本文共 14319 字,大约阅读时间需要 47 分钟。

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 -ListAvailable PS 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 file       Author : 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)            .INPUT    Input Server text file    Service list   .OUTPUTS    JSON output, console   .NOTES    Version:        1.0    Author:         Prashanth Jayaram    Creation Date:  2017-03-08    Purpose/Change: Initial script development    Use 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 = $servername                  name =  $item.name                  Status = $item.Status                   startmode = $item.startmode                   state = $item.state                  serviceaccount=$item.startname                  DisplayName =$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 file invoke-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   FROMOPENROWSET(BULK N'\\hqsqrt05\e$\cu2\Serverice.JSON', SINGLE_NCLOB) AS JSON            CROSS 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 t							CROSS 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.* FROMOPENROWSET(BULK N'\\hqsqrt05\e$\cu2\Serverice.JSON', SINGLE_NCLOB) AS JSON            CROSS 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)

翻译自:

转载地址:http://cgiwd.baihongyu.com/

你可能感兴趣的文章
WordPress资源站点推荐
查看>>
Python性能鸡汤
查看>>
android Manifest.xml选项
查看>>
Cookie/Session机制具体解释
查看>>
ATMEGA16 IOport相关汇总
查看>>
JAVA基础-多线程
查看>>
面试题5:字符串替换空格
查看>>
[Codevs] 线段树练习5
查看>>
Amazon
查看>>
component-based scene model
查看>>
Echart输出图形
查看>>
hMailServer搭建简单邮件系统
查看>>
从零开始学习jQuery
查看>>
Spring+SpringMVC+MyBatis深入学习及搭建(四)——MyBatis输入映射与输出映射
查看>>
opacity半透明兼容ie8。。。。ie8半透明
查看>>
CDOJ_24 八球胜负
查看>>
Alpha 冲刺 (7/10)
查看>>
一款jQuery打造的具有多功能切换的幻灯片特效
查看>>
SNMP从入门到开发:进阶篇
查看>>
@ServletComponentScan ,@ComponentScan,@Configuration 解析
查看>>