Lesson02-SQL2012_AAM_PowerShell Lab

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Lesson 2: PowerShell and WMI

Scripting

Student Lab Manual

Version 1.2

Microsoft | Services © 2013 Microsoft Corporation WorkshopPLUS

Microsoft Confidential
Conditions and Terms of Use
Microsoft Confidential - For Internal Use Only

This training package is proprietary and confidential, and is intended only for uses described in the training materials.
Content and software is provided to you under a Non-Disclosure Agreement and cannot be distributed. Copying or
disclosing all or any portion of the content and/or software included in such packages is strictly prohibited.
The contents of this package are for informational and training purposes only and are provided "as is" without
warranty of any kind, whether express or implied, including but not limited to the implied warranties of
merchantability, fitness for a particular purpose, and non-infringement.
Training package content, including URLs and other Internet Web site references, is subject to change without
notice. Because Microsoft must respond to changing market conditions, the content should not be interpreted to be a
commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented after
the date of publication. Unless otherwise noted, the companies, organizations, products, domain names, e-mail
addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real
company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should
be inferred.

© 2013 Microsoft Corporation. All rights reserved.

Microsoft | Services © 2013 Microsoft Corporation WorkshopPLUS

Microsoft Confidential
Copyright and Trademarks
© 2013 Microsoft Corporation. All rights reserved.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering
subject matter in this document. Except as expressly provided in written license agreement from Microsoft, the
furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other
intellectual property.
Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under
copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose,
without the express written permission of Microsoft Corporation.

For more information, see Use of Microsoft Copyrighted Content at


http://www.microsoft.com/about/legal/permissions/
Microsoft®, Internet Explorer®, and Windows® are either registered trademarks or trademarks of Microsoft
Corporation in the United States and/or other countries. Other Microsoft products mentioned herein may be either
registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. All other
trademarks are property of their respective owners.

Microsoft | Services © 2013 Microsoft Corporation WorkshopPLUS

Microsoft Confidential
Lesson 2: PowerShell and WMI Scripting 5

PowerShell scripting with SQL Server 2012


Introduction
In this lab you will leverage PowerShell and WMI to collect Server, Instance and
Database level information. At the end you will use the collected data to build an HTML
report to show SQL Instances and Databases not confirming to Contoso’s best practices

Objectives
After completing this lab, you will be able to:
 Validate and Set the Execution Policy
 Leverage WMI to pull server level Info
 Use SMO instead of SQLPS to retrieve SQL Server Info
 Build an Advanced Function to simulate a native PowerShell Cmdlet
 Write collected information to a SQL Server Database
 Build an HTML report based on the data collected

Estimated time to complete this lab


60 minutes

Virtual Machines Needed for this Lab:


 SQL11AdminWork
 SQLAdmin11CluN1
 SQLAdmin11CluN2

NOTE: Lab scripts are located on SQL11AdminWork under


L:\Advanced\Labs\Lesson 2 - PowerShell\ServerAudit\

Microsoft | Services © 2013 Microsoft Corporation WorkshopPLUS

Microsoft Confidential
6 Lesson 2: PowerShell and WMI Scripting

Validating the Execution Policy


1. Log into SQL11AdminWork if you are not.
2. Launch PowerShell ISE from your Windows Start Menu using Run As
Administrator if UAC is enabled.
3. In the command pane type the following to see the current execution policy
Get-ExecutionPolicy
4. Validate that the execution policy is set to RemoteSigned.
RemoteSigned

If the execution policy is not set to RemoteSigned, you can use the Set-Execution
policy to set to RemoteSigned.

Set-ExecutionPolicy RemoteSigned

On the Execution Policy Change window, confirm the change by hitting Yes.
5. In the command pane type the following to view the available Modules that can be
loaded:
Get-Module -ListAvailable
Notice SQLPS is a Module that can be loaded
6. Let’s load the SQLPS module. Note, if you are using PowerShell v3.0 the SQL
Server PowerShell provider is loaded the first time you run a SQL Server cmdlet.
Type the following command in the Command Pane.
Import-Module sqlps -DisableNameChecking
Note: This module is loaded only for this session of PowerShell. If you open a new
PowerShell ISE, you will have to import the module again. You can use Profiles
which are outside the scope of this lesson to import the SQLPS module when you
launch PowerShell ISE.
To confirm the module is loaded, type the following and SQLPS should now be
listed.
Get-Module
7. Leave the PowerShell ISE session open for the next task

Microsoft | Services © 2013 Microsoft Corporation WorkshopPLUS

Microsoft Confidential
Lesson 2: PowerShell and WMI Scripting 7

Leveraging WMI to Pull Server Level information


1. Validate that the PowerShell Command Add-On window is visible to the right of the
scripting pane. If not go to View and Select Show Command Add-On

2. In the Name field of the Command Add-On enter WMI


3. Select Get-WMIObject from the list and click the Help Icon
4. Read thru the Help and close when done
5. In the script pane enter the following to get the processor level information
Get-WmiObject -class Win32_Processor -computername SQLAdmin11Clun1
-namespace root\CIMV2
Notice only a couple of parameters are listed.
6. Use the Get-Member cmdlet to see a list of Properties and Methods for objects
generated by Get-WmiObject
Get-WmiObject -class Win32_Processor -computername SQLAdmin11Clun1
-namespace root\CIMV2 | Get-Member
7. There are a couple of additional parameters that would be useful to document. Type
the following to see the specific parameters
Get-WmiObject -class Win32_Processor -computername SQLAdmin11Clun1
-namespace root\CIMV2 |Select PSComputerName, Name, NumberOfCores,
NumberOfLogicalProcessors
8. Now try to run it with an invalid servername
Get-WmiObject -class Win32_Processor -computername BadServer -
namespace root\CIMV2 |Select PSComputerName, Name, NumberOfCores,
NumberOfLogicalProcessors
This may take a couple seconds to return The RPC server is unavailable.
9. To wrap the code with some error handling to deal with the errors, first we need to
set the $ErrorActionPreferece variable to SilentlyContinue then create a custom
object with the same parameters we are collecting as if it were able to connect
successfully. This Custom object will contain parameters to indicate that the script

Microsoft | Services © 2013 Microsoft Corporation WorkshopPLUS

Microsoft Confidential
8 Lesson 2: PowerShell and WMI Scripting

was unable to connect to the server. Update the script in the script pane with the
following (GetProcessorInfoWithErrorHandling.ps1)
cls
$Computer = 'BadServer'
$ErrorActionPreference = 'SilentlyContinue'
$Error.Clear()
$ProcessorConfig = Get-WmiObject -class Win32_Processor -
computername $Computer -namespace root\CIMV2 |Select
PSComputerName, Name, NumberOfCores, NumberOfLogicalProcessors
write-Debug $Error.Count
If ($Error.Count -gt 0)
{
$ProcessorConfig = New-Object psobject
$ProcessorConfig | Add-Member -type NoteProperty -name
PSComputerName ("$Computer-failed to connect")
$ProcessorConfig | Add-Member -type NoteProperty -name Name -
value 'Unable to get ProcessorInfo'
$ProcessorConfig | Add-Member -type NoteProperty -name
NumberOfCores -value $null
$ProcessorConfig | Add-Member -type NoteProperty -name
NumberOfLogicalProcessors -value $null
Write-Debug "Failed to connect to $Computer"
}
$ErrorActionPreference = 'Continue'
$ProcessorConfig | FT * -AutoSize

10. In the Command Pane change the value for $DebugPreference to Continue and re-run
the above script to see the Debug Message.
$DebugPreference = 'Continue'
You should now see the following message displayed in the Command Pane
DEBUG: Failed to connect to BadServer

Microsoft | Services © 2013 Microsoft Corporation WorkshopPLUS

Microsoft Confidential
Lesson 2: PowerShell and WMI Scripting 9

Leveraging SMO to retrieve database level information


1. Open PowerShell ISE if it is not already open and in the Script Pane type the
following to load the SQLPS module, connect to a SQL Server instance via
PowerShell and use Get-Member to see the list of Properties and Methods of the
instance
cls
Import-Module SQLPS -DisableNameChecking
CD SQLSERVER:\SQL\SQLAdmin11CluN1\Default
Get-Item . | Get-Member
Note: It may take a while to load the SQLPS Module
2. Scroll to the top and note the TypeName, which is the Class that the ServerInstance
belongs to. Scroll thru the output and observe the various properties and methods
3. Navigate the databases folder, by typing the following in the script pane
Cd Databases
<Hit Enter to Navigate to the Databases Folder i.e>
PS SQLSERVER:\sql\SQLADMIN11CluN1\default\databases>
4. Use Get-Member to see the list of Properties and methods of a database object by
typing the following the command pane and review the properties, methods and
TypeName.
DIR | Get-Member
5. Close all PowerShell ISE sessions and Restart PowerShell. This will remove the
SQLPS module and show the performance difference of just loading the
Microsoft.SqlServer.Smo assembly as compared to the entire SQLPS Module.
6. Paste the following into the Script Pane and run it
(ConnectToServer_SMO_Part1.ps1)
#Load the Assembly to connect to the SQL Instance
Add-Type -Path
'C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.Smo\11.0.0.0__89
845dcd8080cc91\Microsoft.SqlServer.Smo.dll'
$SrvConn = new-object
Microsoft.SqlServer.Management.Common.ServerConnection
$SrvConn.ServerInstance='SQLADMIN11CluN1'
#Use Integrated Authentication
$SrvConn.LoginSecure = $true
$SrvConn.ConnectTimeout = 1
$srv = new-object
Microsoft.SqlServer.Management.SMO.Server($SrvConn)
$dbs = $srv.Databases
7. In the Command Pane type the following to see the Properties and Methods
$DBs | Get-Member
8. Now that we have a list of databases, let’s loop thru each database and extract some
key pieces of information to build the audit report. Open the script
ConnectToServer_SMO_Part2.ps1, examine the changes to the above and run the
script.

Microsoft | Services © 2013 Microsoft Corporation WorkshopPLUS

Microsoft Confidential
10 Lesson 2: PowerShell and WMI Scripting

Building an Advanced Function to pull Database Info


1. Close all existing PowerShell ISE Windows and open a new one
2. In the script pane, right click and choose Start Snippets
3. Scroll thru the list of snippets and select cmdlet(advanced function) – complete.
Examine the structure of a Complete Function.
4. Close the script pane with the Advanced Function template
5. Open the file ConnectToServer_SMO_Part3.ps1 which builds upon the previous
exercise, but converts it to an advanced function and also adds some error handling.
Notice at the top in the Param section we define the parameters of the function and
also that it can accept the process from the pipline. Read thru the comments in green
in the script as this will explain some of the details of the script.
6. Run the script to load in your session.
7. To look at the help options for this newly created Advanced Function run the
following in the command pane, and review the help and examples
Get-Help Get-DBLevelInfo -Detailed
8. Run the following command in the command pane
Get-DBLevelInfo
Notice as you’re typing Get-DBLevelInfo, the predictive text recognizes the cmdlet.

9. Since no parameter for the SQLInstance was specified, you are now prompted. At the
Prompt type SQLAdmin11CluN1
SQLInstance: SQLAdmin11CluN1
You should see the DB Level information in the Command Pane now.
10. To take advantage of the SQLInstance Parameter for Get-DBLevelInfo to be able to
accept input from the pipeline type the following command which will read the
contents of a text file with a list of servers to scan, then inspect the database
properties of each server. In the command pane enter
get-content 'L:\Advanced\Labs\Lesson 2 -
PowerShell\ServerAudit\ServerList.txt' | Get-Dblevelinfo

Microsoft | Services © 2013 Microsoft Corporation WorkshopPLUS

Microsoft Confidential
Lesson 2: PowerShell and WMI Scripting 11

Writing to SQL Server


In this exercise, we will be using the pre-built scripts from the MS Scripting Center
Out-DataTable to convert a PowerShell object to a DataTable that can be bulk
inserted into SQL Server with the Write-DataTable function. These can be found
from:
http://gallery.technet.microsoft.com/scriptcenter/4208a159-a52e-4b99-83d4-
8048468d29dd
http://gallery.technet.microsoft.com/scriptcenter/2fdeaf8d-b164-411c-9483-
99413d6053ae
1. Close all existing PowerShell ISE Windows and open a new one
2. Open the file WriteDBLevelInfoToSQL.ps1
3. Step thru the script reading the comments. The biggest change to this compared to the
script in the previous example is we are now formatting the output and writing to
SQL Server

Building an HTML Report from the Data collected


1. Close all existing PowerShell ISE Windows and open a new one
2. Open the file DBConfigReport.ps1
3. Step thru the script reading the comments and run it. This will produce an HTML
Report from the data that we collected from the previous exercise.

Putting it all together into a more comprehensive report


1. Close all existing PowerShell ISE Windows and open a new one
2. Open the file Final_RunServerAudit.ps1
3. Step thru the script reading the comments and run it. This will create the audit
schema and check various server level, Instance level and database level
configurations that are not following Contoso’s Best Practice Guidelines.
4. Run the Script to populate the data
5. Open the file Final_GenerateReports.ps1. This will create 2 HTML reports. 1 for
databases not following proper backup procedures and 1 for instances not following
Best Practice guidelines.

Microsoft | Services © 2013 Microsoft Corporation WorkshopPLUS

Microsoft Confidential

You might also like