Getting started with Powershell for the DBA

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

Week 6: Chapter 6 Agenda Automation of SQL Server tasks using: SQL Server Agent Scheduling Scripting Technologies.
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
James Boother Blog: INTRODUCTION TO POWERSHELL.
PHP (2) – Functions, Arrays, Databases, and sessions.
Great people, great experience, great passion Administering SharePoint with Windows PowerShell Go Beyond the Management Shell with SharePoint and Windows.
ASP.NET Programming with C# and SQL Server First Edition
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
DEMONSTRATION FOR SIGMA DATA ACQUISITION MODULES Tempatron Ltd Data Measurements Division Darwin Close Reading RG2 0TB UK T : +44 (0) F :
1 Chapter Overview Creating a User Database Setting Database Options Managing User Database Size Placing Database Files on Multiple Disks.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
MySQL + PHP.  Introduction Before you actually start building your database scripts, you must have a database to place information into and read it from.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Appendix A Starting Out with Windows PowerShell™ 2.0.
Winrunner Usage - Best Practices S.A.Christopher.
IT 456 Seminar 5 Dr Jeffrey A Robinson. Overview of Course Week 1 – Introduction Week 2 – Installation of SQL and management Tools Week 3 - Creating and.
Implementing and Using the SIRWEB Interface Setup of the CGI script and web procfile Connecting to your database using HTML Retrieving data using the CGI.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
 It is Microsoft's new task-based command- line shell and scripting language designed especially for system administration.  It helps Information Technology.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Continuous Deployments using SSDT
Rob Sewell Making PowerShell Useful Real-Life Examples of Powershell in Action Slides available here -
Introduction to SQL Server Automation with Powershell by Chris Sommer.
Automation Testing- QTP Rajesh Charles Batch No: Date: jan
SQL Database Management
Web Database Programming Using PHP
SSIS Templates, Configurations & Variables
ASP.NET Programming with C# and SQL Server First Edition
Unit 2 Technology Systems
Stress Free Deployments with Octopus Deploy
Development Environment
Introduction to Database Processing with ADO.NET
What Is The SSIS Catalog and Why Do I Care?
Essentials of UrbanCode Deploy v6.1 QQ147
Working in the Forms Developer Environment
Data Virtualization Tutorial: Introduction to SQL Script
Data Virtualization Demoette… Custom Java Procedures
SQL and SQL*Plus Interaction
Achieve more in less time using the new SQL PowerShell
Loops BIS1523 – Lecture 10.
Data Virtualization Tutorial… OAuth Example using Google Sheets
Introduction to PowerShell
Web Database Programming Using PHP
Dynamic SQL: Writing Efficient Queries on the Fly
PYTHON: AN INTRODUCTION
Current outstanding balance
SQL Server Monitoring Overview
JavaScript: Functions.
Course Name: QTP Trainer: Laxmi Duration: 25 Hrs Session: Daily 1 Hr.
Introduction to Events
Getting Started with the Data ONTAP PowerShell Toolkit
DevOps Database Administration
Azure Automation and Logic Apps:
ISC440: Web Programming 2 Server-side Scripting PHP 3
SQL Server and PowerShell Let’s Get Serious
DevOps Database Administration
Making PowerShell Useful
File Handling Programming Guides.
dbatools - PowerShell and SQL Server Working Together
Developing a Model-View-Controller Component for Joomla Part 3
Arrays
PowerShell Best Practices for SQL DBA’s
Making PowerShell Useful
Cmdlets “Command-lets”
Presented by : Chirag Dani & Dhaval Shah
Grow Your Script From Simple to Module
Gold Sponsors.
Michael Wall Senior DBA, Great Western Malting
Michelle Haarhues Keeping up with SSMS.
Fast-Track UiPath Developer Module 2: Getting to Know UiPath Studio
Presentation transcript:

Getting started with Powershell for the DBA Matthew Darwin

A little about me! Twitter: @EvoDBA Blog: https://naturalselectiondba.wordpress.com Worked with SQL Server since 2008, as both a developer and a DBA. Especially interested in performance tuning, bulk operations and automation. When not working with SQL, I play the saxophone and snowboard!

Why Powershell? I hate manual tasks! I hate repetitive tasks! T-SQL is great for automation on a single server; but I manage lots of servers. Powershell allows me to manage multiple servers from a single console. Why Powershell? Click through each item on the list. Stress how powershell is great for devops style tasks, automation across a bunch of servers. Twitter: @EvoDBA #manssug

Use the Powershell ISE Allows multiple scripts to be open. More visually oriented; colour coded code for ease of reading. Allows you to run highlighted sections of your code using F8. Default install location: C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe Recommend adding to taskbar Twitter: @EvoDBA #manssug

Determining which version of Powershell you’re using Functionality between versions varies massively - more on this later. My recommendation: ensure using at least Powershell 4.0! Use $PSVersionTable.PSVersion.Major to identify which version running. Above is not compatible with Powershell 1.0, so you can then use $host.Version instead. But just install 4.0 or above! Be careful using the Powershell option from SQL Server Agent, in SQL Server 2012 or less, this is Powershell version 2.0, regardless of what you install! Not sure what PS version SQL Server 2014 runs by default. Recommend using the command line instead. Some differences in particular are error handling and output pipeline of error handling. Twitter: @EvoDBA #manssug

Creating a Powershell Profile Useful way of ensuring your session is configured the way you want it and all useful modules are available every time you open a console: the script runs on start-up. Is essentially just a Powershell script, so anything you can do in powershell you can add to your profile. Is referenced in Powershell by $profile. Twitter: @EvoDBA #manssug

Creating a Profile - Demo Walk through demo at D:\Users\MDarwin\Documents\SQLServerUserGroup\PowershellForTheDBA\1. Setup - Creating A Profile & Importing Modules Twitter: @EvoDBA #manssug

Objects not variables Powershell uses objects, not variables. Objects are typed; these can be simple, such as int, string etc, but can also be much more complex. Use New-Object to create a new powershell object. Cast a variable as a type using square brackets, e.g. [int]$Number = 1. Also a type of PSObject which allows us to create custom properties for our object. Twitter: @EvoDBA #manssug

These are the ones I probably use the most! Get-Member - displays the properties & methods of a type. Write-Output - what it says on the tin - writes the output to the output pipeline. Write-Verbose - allows switchable printing of text. ForEach - loops through a collection. Get-Childitem - gets child objects from an object. New-Object - creates a new object. Common Commands These are the ones I probably use the most! Click through each item on the list. Write-Verbose writes to a different output pipeline than Write-Output Twitter: @EvoDBA #manssug

Using common commands - Demo Walk through demo at D:\Users\MDarwin\Documents\SQLServerUserGroup\PowershellForTheDBA\2. Common Commands Twitter: @EvoDBA #manssug

Functions allow you to easily call a block of code. Modules allow you to load functions, or sets of functions. Functions and Modules Personally, I like to keep my modules as single functions, for ease when it comes to source control and so on. Then use a module manifest (beyond the scope of this) to bring them together into a single module Twitter: @EvoDBA #manssug

Creating a function function My-Function { #code to run here } It’s as simple as that. Twitter: @EvoDBA #manssug

Function parameters Use [Cmdletbinding()] for inbuilt functions like verbose, debug etc. Specify input parameters using param([type]$Parameter, n…) Parameters are then passed in using -Parameter Value. List of approved verbs can be displayed using Get-Verb. Twitter: @EvoDBA #manssug

Creating a function - Demo Twitter: @EvoDBA #manssug

Creating a module The simplest type of module is a .psm1 file. Use the Export-ModuleMember cmdlet to export the components of the module. You can reference multiple .psm1 files in a module manifest. I like to keep a single function in a psm1 file for ease of source control use; then bring them together with a module manifest (Beyond the scope of this demo). Twitter: @EvoDBA #manssug

Making a Module - Demo Twitter: @EvoDBA #manssug

Connecting to SQL Server in Powershell Invoke-Sqlcmd Out-Datatable & Import-SQLData Microsoft.Sqlserver.Management.Smo Connecting to SQL Server in Powershell Twitter: @EvoDBA #manssug

Invoke-Sqlcmd Allows us to run T-SQL statements against a server. Data returned can be stored in an object of System.Data.DataRow type; this can be used in foreach loops etc. The -variables parameter allows us to pass in SQLCMD variables. Useful for retrieving data for manipulation in our powershell scripts, e.g. a list of servers. Twitter: @EvoDBA #manssug

Invoke-Sqlcmd - Demo Twitter: @EvoDBA #manssug

Out-DataTable and Import-SqlData To import data, we first need to convert our object to a typed row object. Chad Miller has written a function named Out-DataTable which does this for us; download from https://gallery.technet.microsoft.com/scriptcenter/4208a159-a52e-4b99- 83d4-8048468d29dd I’ve written Import-SqlData to make it easy to load this object into a table. This uses the sqlbulkcopy method so must follow bulk insert rules. Twitter: @EvoDBA #manssug

Out-DataTable and Import-SqlData - Demo Twitter: @EvoDBA #manssug

The SMO (Server Management Objects) Create a server object with Microsoft.SqlServer.Management.Smo.Server Able to run server level config from here using .Configuration. Can loop through the databases on the server using the .Databases collection, and administer them from there. Same then applies for objects within the database, such as tables, views, procedures and so on. Twitter: @EvoDBA #manssug

Using the SMO - Demo Twitter: @EvoDBA #manssug

Why not just configure Model? Model only allows a single filegroup. I like to keep my user data out of the PRIMARY filegroup. Allows me to set the Database Owner on creation. Allows me to set the Recovery Model on creation. Allows easy override of file locations/sizes & ensure no percentage growth. New-SQLDatabase Why not just configure Model? Twitter: @EvoDBA #manssug

New-SQLDatabase - Required Parameters TargetServer - the SQL Server you wish to create the DB on. DatabaseName - what your shiny new DB will be called. NumberOfFilesInUserFileGroup - the number of files that will be added to your user filegroup (NOT the PRIMARY filegroup). UseDefaultFileLocations - boolean whether you wish to use the defaults, if not need to populate:- NonDefaultFileLocation NonDefaultLogLocation Twitter: @EvoDBA #manssug

New-SQLDatabase - Optional Parameters Collation - what collation you want to use, if left blank the server default will be used. RecoveryModel - which recovery model we’ll use; defaults to the model db recovery model. DatabaseOwner - the account that will own the db. Defaults to the sa account. (I might change that….) Twitter: @EvoDBA #manssug

New-Database - Growth options UserDataFileSize - size in MB of the files in the user filegroup; all files will be the same size. UserDataFileMaxSize - max size in MB for the user files. UserDataFileGrowth - autogrowth size in MB. Use 0 for no autogrowth. LogSize - as above, but for the log. LogGrowth - ditto. Twitter: @EvoDBA #manssug

New-SQLDatabase - Demo Twitter: @EvoDBA #manssug

Export-TableScripts Uses the SMO scripter class to script objects. Takes an array of table names, or scripts all tables in a database. Partition schemes are included, otherwise the filegroup is left to the default. Export-TableScripts Twitter: @EvoDBA #manssug

Export-TableScripts - Demo Twitter: @EvoDBA #manssug

Putting it together - Demo Twitter: @EvoDBA #manssug

Powershell allows configurable automation of routine tasks. It can help with multi server automation. Reusable code can be employed over and over again. The power of .Net can be combined with T-SQL. Wrapping Up Twitter: @EvoDBA #manssug