Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
SQL Server 2012 with PowerShell V3 Cookbook

You're reading from   SQL Server 2012 with PowerShell V3 Cookbook

Arrow left icon
Product type Paperback
Published in Oct 2012
Publisher Packt
ISBN-13 9781849686464
Length 634 pages
Edition 1st Edition
Concepts
Arrow right icon
Author (1):
Arrow left icon
Donabel Santos Donabel Santos
Author Profile Icon Donabel Santos
Donabel Santos
Arrow right icon
View More author details
Toc

Table of Contents (21) Chapters Close

SQL Server 2012 with PowerShell V3 Cookbook
Credits
About the Author
Acknowledgement
About the Reviewers
www.PacktPub.com
Preface
1. Getting Started with SQL Server and PowerShell FREE CHAPTER 2. SQL Server and PowerShell Basic Tasks 3. Basic Administration 4. Security 5. Advanced Administration 6. Backup and Restore 7. SQL Server Development 8. Business Intelligence 9. Helpful PowerShell Snippets SQL Server and PowerShell CheatSheet PowerShell Primer Resources Creating a SQL Server VM Index

Basics—points to remember


Let's explore some PowerShell basic concepts.

Cmdlets

Cmdlets, pronounced as "commandlets", are the foundation of PowerShell. Cmdlets are small commands, or specialized commands. The naming convention for cmdlets follows the Verb-Noun format, such as Get-Command or Invoke-Expression.

PowerShell V3 boasts a lot of new cmdlets, including cmdlets to manipulate JSON (ConvertFrom-Json, ConvertTo-Json), web services (Invoke-RestMethod, Invoke-WebRequest), and background jobs (Register-JobEvent, Resume-Job, Suspend-Job). In addition to built-in cmdlets, there are also downloadable community PowerShell extensions such as SQLPSX, which can be downloaded from http://sqlpsx.codeplex.com/.

Many cmdlets accept parameters. Parameters can either be specified by name or by position. Let's take a look at a specific example. The syntax for the Get-ChildItem cmdlet is:

Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] 
[-Include <string[]>] [-Exclude <string[]>] 
[-Recurse] [-Force] [-Name] 
[-UseTransaction] [<CommonParameters>] 

The Get-ChildItem cmdlet gets all the "children" in a specified path. For example, to get all files with a .txt extension in the C:\Temp folder, we can use Get-ChildItem with the –Path and –Filter parameters:

Get-ChildItem -Path "C:\Temp" -Filter "*.csv"

We can alternatively omit the parameter names by passing the parameter values by position. When passing parameters by position, the order in which the values are passed matters. They need be to in the same order in which the parameters are defined in the Get-ChildItem cmdlet:

Get-ChildItem "C:\Temp" "*.csv"

To learn the order in which parameters are expected to come, you can use the Get-Help cmdlet:

Get-Help Get-ChildItem

Learning PowerShell

The best way to learn PowerShell is to explore the cmdlets, and try them out as you learn them. The best way to learn is to explore. Young Jedi, you need to get acquainted with these three (3) cmdlets: Get-Command, Get-Help, and Get-Member.

Get-Command

There are many cmdlets. And that list is just going to get bigger. It will be hard to remember all the cmdlets except for the handful you use day in and day out. Besides using the search engine, you can use the Get-Command cmdlet to help you look for cmdlets.

Here are a few helpful cmdlets:

  • To list all cmdlets:

    Get-Command
    
  • To list cmdlets with names that match some string patterns, you can use the –Name parameter and the asterisk (*) wildcard:

    Get-Command -Name "*Event*"
    
  • To get cmdlets from a specific module:

    Get-Command -Module SQLASCMDLETS
    

Get-Help

Now that you've found the command you're looking for, how do you use it? The best way to get help is Get-Help (no pun intended). The Get-Help cmdlet provides the syntax of a cmdlet, examples, and some additional notes or links where available.

Get-Help Backup-SqlDatabase
Get-Help Backup-SqlDatabase –Examples
Get-Help Backup-SqlDatabase -Detailed
Get-Help Backup-SqlDatabase -Full
Get-Help Backup-SqlDatabase -Online #opens browser

The different parameters—Examples, Detailed, Full, and Online—will determine the amount of information that will be displayed. The Online parameter opens up the online help in a browser.

Get-Member

To really understand a command or an object and explore what's available, you can use the Get-Member cmdlet. This will list all the properties, methods of an object, or anything incoming from the pipeline.

$dt = (Get-Date)
$dt | Get-Member

Starter notes

We are almost ready to start learning the syntax. However, here are a few last notes, some points to keep in mind about PowerShell as you learn it. Keep a mental note of these items, and you are ready to go full steam ahead.

PowerShell is object oriented, and works with .NET

PowerShell works with objects, and can take advantage of the objects' methods and properties. PowerShell can also leverage the ever-growing .NET framework library. It can import any of the .NET classes, and reuse any of the already available classes.

You can find out the base class of an object by using the GetType method, which comes with all objects.

$dt = Get-Date
$dt.GetType() #DateTime is the base type

To investigate an object, you can always use the Get-Member cmdlet.

$dt | Get-Member

To leverage the .NET libraries, you can import them in your script. A sample import of the .NET libraries follows:

#load the Windows.Forms assembly
Add-Type -AssemblyName "System.Windows.Forms"

There will be cases when you may have multiple versions of the same assembly name. In these cases, you will need to specify the strong name of the assembly with the Add-Type cmdlet. This means you will need to supply the AssemblyName, Version, Culture, and PublicKeyToken:

#load the ReportViewer WinForms assembly
Add-Type -AssemblyName "Microsoft.ReportViewer.WinForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"

To determine the strong name, you can open up C:\Windows\assembly and navigate to the assembly you want to load. You can either check the displayed properties, or right-click on the particular assembly and select Properties.

Cmdlets may have aliases or you can create one

We may already know some scripting or programming languages, and may already have preferences on how we do things. For example, when listing directories from the Command Prompt, we may be on autopilot when we type dir. In PowerShell, listing directories can be accomplished by the Get-ChildItem cmdlet. Fear not, you can still use dir if you prefer. If there is another name you want to use instead of Get-ChildItem, you can create your own alias.

To find out aliases of a cmdlet, you can use Get-Alias. For example, to get the aliases of Get-ChildItem, you can execute:

Get-Alias -Definition "Get-ChildItem"

To create your own alias, you can use New-Alias:

New-Alias "list" Get-ChildItem

Here are some of the common aliases already built-in with PowerShell:

Cmdlet

Alias

Foreach-Object

%, Foreach

Where-Object

?, Where

Sort-Object

Sort

Compare-Object

compare, diff

Write-Output

echo, write

help

man

Get-Content

cat, gc, type

Get-ChildItem

dir, gci, ls

Copy-Item

copy, cp, cpi

Move-Item

mi, move, mv

Remove-Item

del, erase, rd, ri, rm, rmdir

Get-Process

gps, ps

Stop-Process

kill, spps

Get-Location

gl, pwd

Set-Location

cd, chdir, sl

Clear-Host

clear, cls

Get-History

h, ghy, history

You can chain commands

You can take the result from one command and use it as an input to another command. The operator to chain commands is a vertical bar (|) called pipe. This feature makes PowerShell really powerful. This can also make your statements more concise.

If you are familiar with the Unix/Linux environment, pipes are a must-have and are incredibly valuable tools.

Let's take an example. We will export the newest log entries (time and source fields only) to a text file in JSON format:

  1. We need to get the newest log entries:

    Get-EventLog -LogName Application -Newest 10
  2. We need only the time and source fields. Based on what we get from step 1, we need to excute the following query:

    Select Time, Source
  3. We need to convert to JSON. Using step 2 results as input, we need to execute the following query:

    ConvertTo-Json
  4. We need to save to a file. We now want to take what we have in step 3 and put it into a file:

    Out-File -FilePath "C:\Temp\json.txt" -Force
  5. The full command will be:

    Get-EventLog -LogName Application -Newest 10 | 
    Select Time, Source | 
    ConvertTo-Json | 
    Out-File -FilePath "C:\Temp\json.txt" -Force

This is just a simple example of how you can chain commands, but should give you an idea how it can be done.

Filter left, format right

When you chain commands, especially when your last actions are for formatting the result, you want to do this as efficiently as possible. Otherwise, you may use a lot of resources to format data, and end up only needing to display a few. It is best to trim your data first, before you pass them down the pipeline for formatting.

Package and reuse

Functions and modules allow you to package up the logic you built in your scripts, and put it in reusable structures. A function can be simply described as a callable code block. A module allows you to put together a library of variables and functions that can be loaded into any session, and allow the use of these variables and functions.

Your goal should be to package up most of what you've already built in scripts, and put it into functions, and later compile them into a module. Note that you can also create your functions so they behave like cmdlets.

Note

Converting your scripts into functions is tackled at a later section in this appendix.

Common Cmdlets

Typically, cmdlets are categorized to their main purpose or functionality based on the verb used in their name. Here is a partial list of cmdlets to explore. Note that many cmdlet names are self-documenting:

Category

Cmdlet

Utility

ConvertFrom-Csv

ConvertFrom-Json

ConvertTo-Csv

ConvertTo-Html

ConvertTo-Json

ConvertTo-Xml

Export-Clixml

Export-Csv

Format-List

Format-Table

Get-Alias

Get-Date

Get-Member

Import-Clixml

Import-Csv

Read-Host

Management

Get-ChildItem

Get-Content

Get-EventLog

Get-HotFix

Get-Process

Get-Service

Get-WmiObject

New-WebServiceProxy

Start-Process

Start-Service

Security

ConvertFrom-SecureString

ConvertTo-SecureString

Get-Credential

Get-ExecutionPolicy

Set-ExecutionPolicy

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image