Presentation is loading. Please wait.

Presentation is loading. Please wait.

Getting started with Powershell for the DBA

Similar presentations


Presentation on theme: "Getting started with Powershell for the DBA"— Presentation transcript:

1 Getting started with Powershell for the DBA
Matthew Darwin

2 A little about me! Twitter: @EvoDBA
Blog: 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!

3 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. #manssug

4 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 #manssug

5 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 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. #manssug

6 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. #manssug

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

8 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. #manssug

9 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 #manssug

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

11 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 #manssug

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

13 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. #manssug

14 Creating a function - Demo
#manssug

15 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). #manssug

16 Making a Module - Demo #manssug

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

18 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. #manssug

19 Invoke-Sqlcmd - Demo #manssug

20 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 83d d29dd 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. #manssug

21 Out-DataTable and Import-SqlData - Demo
#manssug

22 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. #manssug

23 Using the SMO - Demo #manssug

24 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? #manssug

25 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 #manssug

26 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….) #manssug

27 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. #manssug

28 New-SQLDatabase - Demo
#manssug

29 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 #manssug

30 Export-TableScripts - Demo
#manssug

31 Putting it together - Demo
#manssug

32 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 #manssug


Download ppt "Getting started with Powershell for the DBA"

Similar presentations


Ads by Google