SQLvariations: SQL Server, a little PowerShell, maybe some Hyper-V Rotating Header Image

PowerShell

PowerShell

PowerShell Week at SQL University – Post 4

Recap

So far we’ve walked though how to turn on PowerShell and add modules, adding SQL Server 2008 snapins and using PowerShell variables, what cmdlets and functions are, what providers are and how to work with methods & properties.

Profiles

PowerShellProfilesToday we focus on load things in our profile so that they are always available in PowerShell.  First, some basics:

What is a Profile?  A profile is nothing more than a PowerShell script that gets run as soon as you open up a given PowerShell window.

Why would we want to do this?  I use PowerShell almost exclusively for automating work with my SQL Servers.  When I’m ready to do something I don’t want to start by reloading the same toolset every time I open it. I want to click the icon and be ready to go.  The profile saves me from this repetitive loading.  I update my profile as I find cool new scripts that I want to add.

You are not limited to using a single profile in PowerShell.  Personally, I use one of three profiles depending on the task at hand.  Here is how that works. I use the PowerShell ISE or other third party products as my primary way of writing PowerShell scripts (.ps1) and rarely use the “console.”   I only use the console if I need to troubleshoot something that might have to do with STA/MTA. 

When I open up the PowerShell ISE it’s uses it’s own profile CurrentUserCurrentHost that is stored in C:\Users\USERNAME\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1 (picture-right).  Inside of that file on my machine it currently looks like this:

import-module ISEPack
cd C:\Users\Aaron\Documents\PoSh\Load
. ./invoke-sqlcmd2.ps1
. ./Write-DataTable.ps1
. ./Out-DataTable.ps1
. ./Add-SqlTable.ps1
. ./Export-CSV-Append.ps1
. ./invoke-sqlcommand.ps1
. C:\Users\Aaron\Documents\PoSh\Tasks\Get-DisksSpace.ps1
cd c:\temp\

Whatever is in this file only gets loaded into my session when I open the ISE.  Nothing above gets run when I open up the console.  These are items I use in ISE, but not in the console PowerShell window.

There are items I use in both ISE and the console.  These items live in a “super profile” of sorts since I want these items no matter how I access PowerShell CurrentUserAllHosts (which is located in C:\Users\USERNAME\Documents\WindowsPowerShell\profile.ps1). Profile.ps1 (picture-center) gets run every time I open up any PowerShell “host” including 3rd party tools.  This also includes the SQLPS host which may cause errors messages to appear when you open it or run a SQL Agent Job.  These error messages don’t impact a PowerShell step in a SQL Agent Job from running.

Here’s what I have inside of my Profile.ps1 file.

Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Import-Module SQLServer

Whenever I open the ISE both the Microsoft.PowerShellISE_profile.ps1 and the Profile.ps1 scripts get run.

PowerShell.exe (the little blue “host”) has it’s very own CurrentUserCurrentHost profile that it loads.  That’s the exact same name as the profile that we talked about the ISE loading so does that mean that it’s loading that same file?  No.  Each one is configured to load it’s own CurrentUserCurrentHost from a different location.  So if there are items I want in console world only I have a place to store them thanks to C:\Users\USERNAME\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.  Since I rarely use the console my profile there sat empty until recently.  I only added items after I spotted a post by Oisin Grehan ( blog | twitter ) on Implementing a Matrix-Style Console Screen Saver and I HAD to try it.  This only works in the console and not in the ISE so it made my console profile the perfect place for implementing this.  Now my PowerShell_profile.ps1 file (picture-left) looks like this:

Import-Module screensaver
set-screensavertimeout (new-timespan -minutes 5)
enable-screensaver
Start-ScreenSaver

To edit one of the profiles that only load for the console or the ISE all you have to do is open them up and run notepad $profile.  It will figure out which file is the right one for that environment and open it for you.  To edit the profile that is run in every PowerShell environment just run notepad $profile.CurrentUserAllHosts.  If your WindowsPowerShell directory isn’t there it will not automatically create that for you and you will get an error message stating that it “can’t find the specified path“.  I’ve written a little script to check for that and create one for you if it’s not already there:

$myPowerShell = $HOME
$myPowerShell +="\Documents\WindowsPowerShell"
if ((Test-Path $myPowerShell) -eq "true") {"$myPowerShell is already there mate"}
else { "you need to make one"
mkdir $myPowerShell  }

Homework Assignment:

Setup one of your profiles to at least have one of the modules from the SQLPSX project and the SQL Server Snapins loaded up every time you start up the PowerShell ISE. Which profile to use is completely up to you.  Feel free to play around with your choices.  Optionally you can also include the Get-DisksSpace function like I do; but you don’t have to.

Let me know how this goes for you by dropping a note it the comments.  In tomorrow’s post we are going to work with multiple SQL Servers so you’ll need these things up and running for that.

If you’re confused by where your files are you can just run this script that I lifted off of the HeyScriptingGuys site to have it tell you where all of the profiles for your session have been loaded from.  Keep in mind that we’re not touching the ones in the Windows directory.

$profile |

Get-Member -MemberType note* |

Format-Table -Wrap -AutoSize -Property name,

@{ Label=“Path”; Expression={$_.definition -replace “System.String”,“”} }

PowerShellProfiles

In Case you would like more to play with…

There is a lot more that can be done with PowerShell Profiles but these are the basics you need to get up and running. If you want to dive deeper check out these posts over on the Hey Scripting Guy Blog.  Go here to download the SQLServer or ISEPack modules; they are both part of larger projects.  If you’d like some of the scripts that I reference in my profile you can grab the Get-DisksSpace one here and I’ll be blogging about the rest later this week.

Be Advised:

Everything that you put into you profile eats up RAM.  Thankfully most scripts are only a few kilobytes.  Keep in mind that the more items you add into your profile the longer that it is going to take to load.

imageIn case you’re wondering if that “Matrix Style Console Screen Saver” is worth having around, here is what it looks like after a few minutes:

That’s all that I’ve got for you today, see you back tomorrow!

SQL Smackdown: SSIS vs. PowerShell

SQLsmackdownI’ll be presenting with Mike Davis ( blog | twitter ) at SQL Saturday #62 this weekend.  I’ll be presenting on a topic that is very near and dear to my heart: Not using SSIS!  And Mike, well lets face it.  I know Mike’s written a book or two on SSIS but about all that Mike will be doing is showing everyone why I love PowerShell so much.  I hear he even picked up a brand new laptop so that BIDS wouldn’t slow him down as much.  I’ll be bringing my old Netbook running multiple instances of SQL Server.  $5 says I still complete my demos in half the time as Mike’s.

Mike says that we’re going to “Square off” but I heard the new SSIS has pretty new rounded corners.  I don’t know about you but that a feature that I’ve been waiting a loooong time for.  I bet he’s going to be doing a lot of talking about what might be in the Denali version of SSIS but I’ll be showing you what 4 or 5 lines of PowerShell can do for you today!  So if you’re looking for something to do around 2:45 Saturday afternoon come see what PowerShell can do for you!

Guest Posts for Hey Scripting Guy Blog on TechNet

imageLate last year I contributed three guest blogger posts to a full week of posts about PowerShell and SQL Server. The posts were published a week before the PASS Summit. In them I tried to not only cover how useful PowerShell is for automating your every day SQL tasks but also the different approaches you have for accomplishing them: PowerShell cmdlet, WMI, SMO, SQL Provider, and .Net.

It’s a huge honor to get the chance to be a guest blogger on Hey Scripting Guy! and I hope these posts were able to make some people’s (o.k. A Lot of People’s) lives easier. Given the number of people checking out PowerShell for the first time based on the comments to my MCM Videos download script I figured I’d call these out today:

Use PowerShell to Obtain SQL Server Database Sizes

Use PowerShell to Change SQL Server Service Accounts

Use PowerShell to Script SQL Database Objects

image

I know that the Hey Scripting Guy! blog is the #1 blog on TechNet but I’m not allowed to know any specifics beyond that. I did however catch this in yesterday’s post: “In general, the articles we published on SQL Server and on SharePoint have been really popular.” So hopefully that means we’ll get to hear some more SQL voices there in the near future. Maybe even in time for SQL Rally, who knows? Winking smile

PowerShell Script to Download SQL MCM Videos

imageMicrosoft has made changes to the Microsoft Certified Master program for SQL Server to make it much more accessible to everyone.  In short if you have the required credentials (MCITP: DBA 2008, DBD 2008), the required skills, and $2,500; you too can become an MCM for SQL Server.  Microsoft has partnered with SQLskills to produce 40 hours of introductory MCM training material videos which they have made freely available to everyone. 

If you’d like more training than just the videos SQLskills has some classes that you can attend.

If you’re like me you’ve either already downloaded the videos or you’re not even reading this right now because you clicked the link and just started downloading the videos.  Smile  Well if you don’t want to spend the rest of your day downloading all of those videos by hand I’ve got a little PowerShell script I think you’ll enjoy.

$wc = new-object net.webclient
[regex]$regex ="(?<url>http://download.microsoft.com/download/./././[0-f]{8}-[0-f]{4}-[0-f]{4}-[0-f]{4}-[0-f]{12}/(?<file>[^>]*?wmv))"
[xml]$xml =  $wc.DownloadString("http://www.microsoft.com/feeds/TechNet/en-us/How-to-videos/SQL_Server_2008_Microsoft_Certified_Master_(MCM)_Readiness_Videos.xml")
$xml.rss.channel.item | foreach {
    if ($wc.DownloadString($_.link) -match $regex)
    {
        $url = $matches.url
        $file =  "$home\Videos\$($matches.file)"
        if (Test-Path $file)
        {Write-Host "$file is already there mate"}
        else {
            Write-Host "Downloading $file"
            $wc.DownloadFile($url,$file)
        }
    }
}

This script will check the RSS feed, connect to all of the links in it, find the first .wmv link that it comes across, then copy that file to your videos directory in your documents folder IF it’s not already there.  If you have to stop this script that’s fine, it will figure out which videos have already been downloaded and skip them*.  If you want to try downloading the .MP4 files instead, just swap out .wmv for .mp4 and you should be all set.  A warning about that though; they seem to be a little more than twice the size of the .wmv files

*This script is written for Windows 7 and maybe for Windows Vista.  You’ll have to edit it yourself for Windows XP or just bug Nic Cain to post one :-)
**IMPORTANT:  I think I have fixed the HTML rendering issues for the code block but you may need to download the script here.

PowerShell First Timers!

First off, welcome to the best addiction that you will ever have!  Since so many people are checking out this post and firing up PowerShell for the first time, I’ve gathered together some useful links.  Here’s one from the ScriptingGuys themselves: How Do I Install PowerShell on Windows 7 and Other Questions 

I have a series of posts you may want to look at to help you get up & running as well as a video I did a while back for MSDN’s geekSpeak:
PowerShell Week Post 0 (5/17)
PowerShell Week Post 1 (5/18)
PowerShell Week Post 2 (5/20)
PowerShell Week Post 3 (5/20)

I’ll blog more later this week about how I put together the script but I wanted to get it into people’s hands ASAP.  Special Thanks go out to Jeremiah Peschka ( blog | twitter ) for not laughing too hard at my first ever attempt at a RegEx as well as Nicolas Cain ( blog | twitter ) & Chad Miller (Blog|Twitter) for giving me pointers on how to use my new RegEx hammer inside of PowerShell.

PowerShell Grab Bag Code

Thanks to everyone who took the time to check out my PowerShell Grab Bag session today for the PowerShell Virtual Chapter of PASS.  Here’s a zip of all the code that I used and the two links I promised to include.

Today’s Code

Quest’s Free PowerShell Commands for Active Directory

Shay Levy’s ( blog | twitter ) WinRar blog post

Happy Scripting!

Presenting for the PowerShell Virtual Chapter of PASS

pass_logo_thumbSorry for the late notice folks but I will be Presenting for the PowerShell Virtual Chapter of PASS today at Noon Eastern.  Today’s session is just going to be a bunch of cool things that I’ve been working on lately but haven’t gotten a chance to present or blog about yet.  I’m still working on one last script but I’ll post the code before the session if I can.  Hope to see you there!

PowerShell Grab Bag

Wednesday December 15, 2010, 12 Noon Eastern Time (GMT -5)
Speaker:  Me
Live Meeting Information Join the meeting

In this short grab bag session we’ll go over a bunch of new scripts that I’ve built over the last few weeks.  Things like:

  • checking free space on mount points,
  • checking SQL agent for failed jobs,
  • polling instances to make sure they’re available,
  • checking the status of log shipping across multiple targets,
  • emailing result sets and
  • scheduling all these with SQL Agent. 
  • Checking remote registries (including why on earth you would ever want to do that?!).
  • Zipping files, even better, we’ll go over how to not zip files that have already been zipped. 
  • The final grab from this session:  for all the Summit attendees out there, I’ll share with you my script to download all the session videos from the 2010 Summit

I’m on the PowerScripting Podcast

PowerScripting PodcastTwo Weeks ago I got to sit around a table with Jon Walz ( blog | twitter ), Hal Rottenberg ( blog | twitter ), Ed Wilson ( blog | twitter ) and Mark Mitchell ( blog | twitter ) to talk about PowerShell and the 2010 PASS Summit. Surprised it only took 48 minutes! Open-mouthed smile It’s always a lot of fun to get to sit around and talk with those guys at any time but I’m glad it was recorded so that their community can hear how we’re using PowerShell in the SQL community.

If you’ve never been to their site (PowerScripting.net) it is PACKED with PowerShell tips! You would be amazed at the cool tips that you can find from shows they did a year or two ago and their all it the show notes.

I hope you enjoy the show oh and sorry B/I people, I didn’t mean any thing by the parsley thing Winking smile

Listen:

Quick Blog: PowerShell Disk and MountPoint Check

I tuned into twitter yesterday for a couple of minutes and found a great conversation going on between Nicolas Cain ( blog | twitter ) and Dave Levy ( blog | twitter ) about checking Disk Space & Mount Points. I really like what they were working on because it was actually one of my top priorities for the week. I already have some code for checking both regular disk drives and mount points with PowerShell but I was looking to improve it and get it ready for production monitoring.

Everyone’s environment is different and they build things based on needs and pain points. For my own environment I took a little of what Dave put together and a little of what Nick put together and built my own function for my environment. I’m still trying to add some more information to it but here’s what I’ve got so far:

Function Get-DisksSpace ([string]$Servername, $unit= "GB")
{
$measure = "1$unit"

Get-WmiObject -computername $serverName -query "
select SystemName, Name, DriveType, FileSystem, FreeSpace, Capacity, Label
  from Win32_Volume
 where DriveType = 2 or DriveType = 3" `
| select SystemName `
        , Name `
        , @{Label="SizeIn$unit";Expression={"{0:n2}" -f($_.Capacity/$measure)}} `
        , @{Label="FreeIn$unit";Expression={"{0:n2}" -f($_.freespace/$measure)}} `
        , @{Label="PercentFree";Expression={"{0:n2}" -f(($_.freespace / $_.Capacity) * 100)}} `
        ,  Label
}#Get-DisksSpace

The code above will create a PowerShell function (sorta kinda like a stored procedure only not really but just think of it like that if you’re a SQL person that’s new to PowerShell Smile ) Here’s how you would call it:

Get-DisksSpace “Win7NetBook” | Format-Table

Or if you only wanted to know about the drives that are low on space:

Get-DisksSpace “Win7NetBook” | where{$_.PercentFree -lt 20} | Format-Table

This will return you the list of drives and mount points on the machine you listed and default the unit of measure to convert the results to gigabytes. The great news is that this code runs really fast. Their conversation yesterday literally saved me hours of work. I’ll keep working with this and post another blog when I put the monitoring portion into production.