Getting Database Tables record and Data Space Used count

I created the function “Get-dbTableRecordCount” to get both the tables record and data space used from a selected table.  A the same time, if you can’t remember the databasename, then you can use the parameter ” -ShowAllDatabases Y ” to only list all databases from the provided SQL Server Instance name.

Download “Get-dbTableRecordCount” Function script at the MS Script Gallery at: http://gallery.technet.microsoft.com/scriptcenter/c606e406-af61-4552-b686-2c9dc17ab06e

A few requirements will remain:

1. Must have either SQL Server 2008 (or above) installed, or the have the free version of SQL Server Management Studio 2008 R2 (no SQL Engine) installed.

2. And, to download either,  or both of the SQLPS modules.  Instructions are provided with the description of the function in the MS Script Gallery.

This functions will have the following 3 parameters:

1. ” -SQLInstanceName “ – This is mandatory entry. Enter your SQL Server instance name.

2. ” -DatabaseName “ – Optional but required with for the “-SQLInstanceName” parameter.

3. ” -ShowAllDatabses “ – Optional but only requiered with the “-SQLInstanceName” parameter and not with “-DatabaseName”.

An Alias name is provided: “gtrc

Also, remember you can use “help”, or “get-help” commands to read documentation about this function.

Sample pics: (show databases only)

gtrc -SQLInstanceName XXXXX -ShowAllDatabases Y
gtrc -SQLInstance XXXXX -DatabaseName YYYYYY

Application: You can save the results adn generate different out results.

Happy scripting!!

Check for SQL Server(s) Version with Get-MSSQLVersion function

I just posted a new PowerShell function to help get information about your SQL Server(s).  Following Don Jones recent post about “Inventory SQL Server Versions on Multiple Computers” this is just to show you, if you have SQL Server 2008 (R2 or above), then you can use SMO which is already installed with SQL.

Check out *”Get-MSSQLVersion” at Script Gallery: http://gallery.technet.microsoft.com/scriptcenter/5f763a6e-23bf-46be-a837-13e5005acb72

Please, make sure to meet the requirements to use this function.  More information in the Script Gallery post.

Now, this new function include three cmdlet parameters that will affect your results.

  • ” -SQLServerOption ” – This parameter will allow you to: 1) Individually get version information about one, or a series of SQL Server, or 2) using the ” -SQLServerOption all ” parameter, will get you a list of all SQL Servers on the network.
  • -DateTimeStamped ” – *This parameter only accepts Y, any other character(s) will be ignored. This will results in writting the start and end date/time for running this command.
  • -HideBlank ” – This parameter only accepts Y, any other character(s) will be ignored.  This will ignored all blanks items selected with the ” -SQLServerOption ALL” because   you may not have permission to access the SQL Instance.

By the way, I automatically included some SQL Server counter to let you know how many server(s) it found and the how many are listed in the results.

*Note: I included the Date/Time stamped is because this function will take some time to complete. 

Sample picture:

Practical Use: – The following line will create a text file with your information:   

PS> gmsv -SQLServerOption ALL | Out-File c:\MyFolder\MySQLVersionInfo.txt

Also, you can save the results to an object, then create a csv file.  Here’s the starting point for your CSV:

Go ahead, and complete the task…  I’m Just Saying!!

 Have fun Scripting!!

Get-dbTableColumns function submitted to the Script Gallery

Based on recent article about getting SQL Server table columns information, I decided to create a function “Get-dbTableColumns.ps1” and posted into the Microsoft Scritp Gallery. I use some of our favorite community tools from Chad Miller and Pinal Dave to bring in a practical and useful command.

So, checked it out at, “Get database table columns list”: http://gallery.technet.microsoft.com/scriptcenter/21c90399-d408-428d-92a5-902e037fdd9b

Instructions are included.

Hint: Want to save result to a text file? Try…

Get-dbTableColumns -DatabaseName YourDbName | Out-File -FilePath c:\TableInfo.txt

Enjoy!

SQL PowerShell – Enchancing Listing your DB Table Information

I love the PowerShell collaboration in the IT community.  One of my twitter followers reminded me about the “Format-Table” command  that allows you to group your collection using the parameter “-GroupBy” which work beautifully.  There’s no need to add the “ForEach” command.  I trully forgot to the check for this parameter. 

This change in my script will saves be  a few more lines of code.and here’s the final result.  Here’s the script:

[sourcecode language=”powershell” 1=”wraplines"false"”]
## – Stored T-SQL modified script into a string variable
$sqlQuery = @"
SELECT
s.name+’.’+OBJECT_NAME(c.OBJECT_ID) as SchemaTableName
,c.name AS ColumnName
,SCHEMA_NAME(t.schema_id) AS SchemaName
,t.name AS TypeName
,c.max_length
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
JOIN sys.tables as t2 on t2.object_id = c.object_id
JOIN sys.schemas as s on s.schema_id = t2.schema_id
ORDER BY c.OBJECT_ID;
"@

## – Load the SQLPS module for Denali ( for 2008/200R2 is SQLPS)
Import-Module SQLPSv2
$SavedResults1 = Invoke-SQLCmd -ServerInstance "ISO-DESKTOP-65" -Database "ReportServer" -Query $sqlQuery
$SavedResults1 | ft -auto -GroupBy SchemaTableName
[/sourcecode]

And, here’s the sample PowerShell Console result:

This is a good example of how PowerShell can keep simplifying your script as yiou continue to grow.

Especial THANKS to David Moravec (http://www.powershell.cz) for tweet to giving me the tip to enhance this script.   Now, you can download both versions:

<>

SQL PowerShell – List your DB Table columns information…

Making some addition to Pinal Dave T-SQL code provided in one of his blog on “List All The Column With Specific Data Types” we can use PowerShell to list our database table’s columns in an efficient way.  But, for the information what I needed to produce I had to add a few things to Pinal’s code.

Keep in mind, PowerShell can assist the DBA in effectively providing better T-SQL results.  Let me show you how we can leverage this T-SQL code with PowerShell.

Here’s the original SQL script executed in SSMS and the actual results shown in the following picture:

(Pinal Dave SQL Script)


This is a start but I needed a little more information, and a better way to display it.

First, I added two other ‘joins’ to the SQL script to include the ‘sys.tables’ and ‘sys.schemas’. Then, I customized the script a little more to get the results I wanted and ran it on my SSMS:

SELECT s.name+‘.’+OBJECT_NAME(c.OBJECT_ID) as SchemaTableName
,c.name AS ColumnName
,SCHEMA_NAME(t.schema_id) AS SchemaName
,t.name AS TypeName
,c.max_length
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
JOIN sys.tables as t2 on t2.object_id = c.object_id   JOIN sys.schemas as s on s.schema_id = t2.schema_id
ORDER BY c.OBJECT_ID;


As you can see, now I included Schema with Table names and removed some columns. Now, let’s put PowerShell in action. I’m going to use my modified T-SQL script, create a simple PowerShell script and run it under SQL PowerShell.

Prerequisite for executing this script, you need to have:

  1. SQL Server 2008 (or above)
    1. Download Chad Miller SQLPS module for SQL Server 2008 and 2008 R2
    2. Or, Download my version of SQLPSv2 for SQL Server ‘Denali’.
  2. PowerShell 2.0

Using the any of the SQLPS modules, you can create a simple PowerShell script to generate our table columns information with a few lines of code:

  1. Store the T-SQL script code in a string variable.
  2. Load the SQL PowerShell Module using the “Import-Module” command.
  3. Run the T-SQL query using the “Invoke-SQLCmd” to store the information in a variable.
  4. Then, we can manipulate the results we just saved in a variable.

Here’s the script:

$sqlQuery = @
SELECT
s.name+’.’+OBJECT_NAME(c.OBJECT_ID) as SchemaTableName
,c.name AS ColumnName
,SCHEMA_NAME(t.schema_id) AS SchemaName
,t.name AS TypeName
,c.max_length
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
JOIN sys.tables as t2 on t2.object_id = c.object_id
JOIN sys.schemas as s on s.schema_id = t2.schema_id
ORDER BY c.OBJECT_ID;
@
Import-Module SQLPSv2
$SavedResults1 = Invoke-SQLCmdServerInstance
“MAX-PCWIN1”Database
“Adventureworks”Query
$sqlQuery
$SavedResults1 | ftauto

The last line of this script will list all content of your stored results and display it in a table format.


We got all tables listed one after another. So, we can add a few more lines of code to separate the tables:

## – First create a list of all the tables in the stored object ‘$SavedResults1’
$TableName = $SavedResults1 | selectunique SchemaTableName | Sort SchemaTableName
## – Verify all tables selected and in order
$TableName

Next step is to use a “ForEach-Object” command to help us break out the tables information individually, and display it on the PowerShell console:

foreach($t
in
$TableName){
    $SavedResults1 | where {$_.SchemaTableName -eq
$t.SchemaTableName} | `
    select SchemaTableName,ColumnName,SchemaName,TypeName,max_length | FTAuto
}


Now, you can be creative in how this information can be displayed, or even exported to another file format such as a ‘CSV’ or ‘TXT’ type. Just try it!!

Here’s the complete simple PowerShell script: 

 

 Stay tuned for more!  

To get script file, download here: 

 

 

Tips on scripting with PowerShell objects…

PowerShell is a great tool for collecting information. Here’s some direct tips to try to minimize the pain of coding, or at  least make it (kind of) readable.  I’ve seen some blogs out there that turn some people way just because their script is working.  But, that’s the beauty of PowerShell.  No matter how you build the code, if the end results is what you’re looking for, then good for you. 

I hope later on you realized that your script can be improved, and you will feel the POWER of POWERSHELL!!!

Briefly, I will be covering PSObject, Hash table, and a bonus Array objects

Check this out.  Here’s an example of some script lines building a PowerShell variable object from two Cmdlets executing two different WMI classes: Win32_OperatingSystem and Win32_BIOS.

Original Sample

   1: $ComputerName = "."

   2: $wmi = Get-WmiObject Win32_OperatingSystem –comp $ComputerName | Select CSName,BuildNumber,ServicePackMajorVersion;

   3: $obj = New-Object PSObject;

   4: $obj | Add-Member NoteProperty BuildNumber ($wmi.BuildNumber);

   5: $obj | Add-Member NoteProperty CSName ($wmi.CSName);

   6: $obj | Add-Member NoteProperty SPVersion ($wmi.ServicePackMajorVersion);

   7: $wmi = Get-WmiObject Win32_BIOS –comp $ComputerName | Select SerialNumber;

   8: $obj | Add-Member NoteProperty BIOSSerial ($wmi.SerialNumber);

   9: $obj;

Now, the above code will work.  In my opinion using Add-Member is already old school. 

image

At the end, I checked for the PS variable ($obj) type, using the “.gettype()” method.  This confirmed this variable a PSCustomObject.

I will show you other ways to get a similar results, and hopefully with less typing.  Maybe, it will look nicer too.  The goal is, as you progress using PowerShell for you day-to-day activity, you will continue to improve your existing code.

Improvement #1

   1: $ComputerName = "."

   2: $wmi1 = Get-WmiObject Win32_OperatingSystem –comp $ComputerName | Select CSName,BuildNumber,ServicePackMajorVersion;

   3: $wmi2 = Get-WmiObject Win32_BIOS –comp $ComputerName | select SerialNumber;

   4:  

   5: $results = $wmi1|select csname,BuildNumber,ServicePackMajorVersion,@{Label=”BIOSSerialNum”;Expression={$wmi2.SerialNumber}};

   6: $results;

As you can see, here I’m first collecting all the information by building my PowerShell variables in $wmi1 and $wmi2 which has different results.  Then, I’m combining the values I want from my $wmi1 and $wmi2 using the “Select” command.

image

So we made some improvements from originally 9 lines of code cut down to 5 lines.  And, notice that the new PS variable type still is “PSCustomObject”.

Now, let me show you another very nice variation that is intended to replace the use of “Add-Member” command.  We are going to use the Hash table concept to create our “PSCustomObject” variable.

Here’s another way which is better looking with less typing than our first example.

Improvement #2

   1: $wmi1 = Get-WMIobject -class Win32_OperatingSystem;

   2: $wmi2 = Get-WmiObject Win32_BIOS

   3:  

   4: $PCHashTable = @{

   5:     BuildNumber  = $wmi1.BuildNumber;

   6:     csname       = $wmi1.csname;

   7:     ServPackVersion = $wmi1.ServicePackMajorVersion;

   8:     BIOSSerialNum   = $wmi2.SerialNumber;

   9: }

  10:  

  11: $MyPSObject = New-Object PSObject -Property $PCHashTable;

  12: $MyPSObject;

image

As you can see, this PowerShell code have 10 lines but, for me, it looks cleaner and easy to read.  Basically, we are breaking the code in three sections:

1. Create the variable objects holding our results.

2. Build the hash table where we combine all our selected objects.

3. Convert the hash table to a “PSCustomObject”, so we can display the results in a proper format.  (see next pic.)

image

Hidden Tips:

Check in both improvement samples (1 & 2), I’m showing how you can create/change the label of your variable property in the “Select” command, and when you are creating a Hash table.

Bonus Script: Using Arrays objects to Collect information

Here’s a snippet you could use the gather information about your SQL Servers using .NET SMO SQL Enumeration to get all SQL names on the network.  To run this script you need to have SQLPS loaded in you PowerShell session and have proper server Windows Authentication.

I hope you’ll like it:

   1: ## For SQL Server need SQLPS to be loaded

   2: ##

   3: $SQLSvr = [Microsoft.SqlServer.Management.Smo.SmoApplication]::EnumAvailableSqlServers($false) | Select name;

   4:  

   5: [Array] $SQLinfo += ForEach($SQL in $SQLSvr){

   6:     $MySQL = new-object(“Microsoft.SqlServer.Management.Smo.Server”) $SQL.Name;

   7:     $MySQL | Select NetName, Product, EngineEdition, Version, Platform, ProductLevel;

   8: } 

   9:  

  10: $SQLinfo | select Netname, Product, EngineEdition, Version, ProductLevel | ft -auto;

Hidden Tip: Notice, I  have created an Array object ($SQLInfo) in line 5, in which the “ForEach()” command will be use to add the results from each element read from the server object ($SQLSvr).

BIG REMINDER!!!  Remember that your PS variables will probably have more values you can display in your results using the “.. |Select val1, val2, val5…”.  Use the Get-member command to exposed them.  (see next pic.)

image

That’s it for now!!

Microsoft Evangelist Blain’s Barton–IT Time Radio…

Yes, East Coast Sr. IT Pro Microsoft Evangelists Blain Barton and John Baker, will be hosting every Friday around noon and IT Radio show.  So, Tuned In, Listen, and participate with these two great speakers.

image

For more information click the following link: http://blogs.technet.com/b/blainbar/archive/2011/02/21/it-time-radio-launches-every-friday-stay-tuned-with-blain-barton-and-john-baker-on-it-topics.aspx

Convert your SQL PS variable results to XML… it’s easy!!

Here’s some PowerShell code use to create a PS variable results from a T-SQL query using the SQL  Server 2008 (or higher) SQLPS command “Invoke-SQLCmd”:

Import-Module SQLPSV2

$SQL1 = @”
Select * from SurfSpotTable
“@

$SQL1Query = Invoke-Sqlcmd -Server ‘MAX-PCWIN1’ -Database ‘Developer’ $SQL1Query

As you can see, with a few lines of code we got back some table information:

 

$SQL1Query

SpotID     SpotName            Location                      State
——       ——–                      ——–                            —–
     1          Wildernes               Aguadilla                     PR
     2         Aviones                   Carolina                       PR
     3         Surfers Beach        Aguadilla                     PR
     4         Jobos                        Isabela                         PR

There’s a couple of things to understand about this code:

1. You need to download either Chad’s Miller SQLPS module for SQL Server 2008 or my SQL Denali SQLPSv2 module version.

2. Need to use the Import-Module to load the SQL Server snapins.

3. Invoke-SQLCmd is using Windows Authentication to connect to the database.

Now, that we have our PS variable “$SQL1Query” then we use the Export-Clixml to export the information to a XML formatted file:

## Convert to XML
$SQL1Query | Export-Clixml -Path createxml.xml -NoClobber -Encoding ASCII

ii createxml.xml

Then, use an XML Editor such as SAPIEN Technologies PrimalXML 2009 to open the file and see the information.  The XML file will look like this:

<Objs Version=”1.1.0.1″ xmlns=”http://schemas.microsoft.com/powershell/2004/04″>
  <Obj RefId=”0″>
    <TN RefId=”0″>
      <T>System.Data.DataRow</T>
      <T>System.Object</T>
    </TN>
    <ToString>System.Data.DataRow</ToString>
    <Props>
      <I64 N=”SpotID”>1</I64>
      <S N=”SpotName”>Wildernes</S>
      <S N=”Location”>Aguadilla</S>
      <S N=”State”>PR</S>
    </Props>
  </Obj>
  <Obj RefId=”1″>
    <TNRef RefId=”0″ />
    <ToString>System.Data.DataRow</ToString>
    <Props>
      <I64 N=”SpotID”>2</I64>
      <S N=”SpotName”>Aviones</S>
      <S N=”Location”>Carolina</S>
      <S N=”State”>PR</S>
    </Props>
  </Obj>
  <Obj RefId=”2″>
    <TNRef RefId=”0″ />
    <ToString>System.Data.DataRow</ToString>
    <Props>
      <I64 N=”SpotID”>3</I64>
      <S N=”SpotName”>Surfers Beach</S>
      <S N=”Location”>Aguadilla</S>
      <S N=”State”>PR</S>
    </Props>
  </Obj>
  <Obj RefId=”3″>
    <TNRef RefId=”0″ />
    <ToString>System.Data.DataRow</ToString>
    <Props>
      <I64 N=”SpotID”>4</I64>
      <S N=”SpotName”>Jobos</S>
      <S N=”Location”>Isabela</S>
      <S N=”State”>PR</S>
    </Props>
  </Obj>
</Objs>

So, with a few lines of code we just produce an XML file from a SQL DataRow results.  You be the judge… but I think this is another example of PowerShell Awesomeness!!

.. I’m Just Saying!!

Stay tuned!! I will have more on PowerShell, SQL, and XML files soon.

PrimalSQL and PrimalForms 2011, a perfect couple…

Here’s a quick overview of both PrimalSQL and PrimalForms 2011 working together.  These products gives you the ability to create GUI PowerShell scripts on the fly so you cut down you scripting time.

PrimalSQL2011

PrimalForms2011

I am test driving the upcoming new SAPIEN Technologies PrimalSQL 2011, and especially the new option to either “Generate Query Form…”, or “Generate Query PowerShell Script…”.   The best is the ability the generate a basic query form that you can change using the new upcoming PrimalForms 2011.  Both products are looking very solid with few bugs, and it’s still not in Beta yet!  It’s impressive.

Here’s both products working together:

PrimalSQLFORMS2011

Stay tuned for more information about this new product releases! 

Checkout more on exporting to a PowerShell script on SAPIEN Technologies blog: http://blog.sapien.com/index.php/2011/01/11/feature-peek-2011-primalsql-exporting-powershell-guis/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+SapienBlog+%28SAPIEN+Technologies+Blog%29