SQL Saturday #86 Tampa BI edition: SSIS – Analyzing your data integrating PowerShell session

I’m excited to bring this new topic to #SQLSat86 Tampa for the BI community.  So, here’s a brief rundown of what I will be covering on Saturday, November 5th morning session:

Topic: SSIS – Analyzing your data integrating PowerShell

*Note: This is not an all PowerShell Session but it plays a big role in this SSIS solution.

What will be covering:

1. Some basic to intermediate SSIS and PowerShell.
2. How to pass arguments between PowerShell and SSIS steps.
3. How to use PowerShell to assist in analyzing our tables and/or Data.
4. How to Integrate PowerShell in our SSIS Solution (when needed).
5. Tool available to allow these two technologies to integrate in our ETL solution.

This is going to be an ALL DEMO session.

Requirements:

1. Have some interest in PowerShell.
2. Some basic SSIS ETL experience.
3. Willing to be open to new technologies.
4. Most Important: No PowerShell experience is not required.

I will Demo:

1. Passing Arguments between PowerShell Applications in SSIS.
2. Work with both Script Task and Script Components.
3. Use of both VB and C# (CSharp) .NET Scripting code.
4. Some PowerShell.

I hope yopu will enjoy this presentation

Posted in PowerShell, SQL Server | Comments Off

PowerShell working with SQLPS or SMO…

Today, while help @meltondba with his SQLPS question on the enumerating jobs history, @LaerteSQLDBA provided a oneliner to provide this result.  There’s one concern, should we use SQLPS instead of SMO.   For this answer I’m going to point out MSDN article regrading the future of SQLPS in upcoming SQL Server releases: http://msdn.microsoft.com/en-us/library/cc280450(v=SQL.110).aspx

This article states that “… This feature will be removed in a future version of Microsoft SQL Server.  Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use the sqlps PowerShell module instead. For more information about the sqlps module, see Import the SQLPS Module. …”

So, during this exercise I found out that I can out with the same number of line for either SQLPS and SMO.  Both giving me the same results.

Here’s some picture ilustrating basic code snippet of both SQLPS and SMO to get some SQL Server Jobs information:

SQLPS sample of getting jobs information

SMO sample of getting jobs information

This pictures shows, it look simple enough.  So, if you’re building SQLPS scripts, you can easily start transitioning your code to SMO.

Posted in PowerShell, SQL Server | Comments Off

Windows Developer Preview – Looking at the Eye of the Storm

There’s no doubt, there’s a bright future with Windows 8 and it does have lots of exciting features.  But,  did everything looks good and easy.  Well, easy!! Not really.

I’m sure I will not be the only person who have experience problems installing Windows 8.  Now, please understand, this not to critize Microsoft in any way.  Every IT PRO and/or Developer will have different scenario, and in one point in time, will have installation issues.

I had a problem trying to install from Windows 7 the new “Windows 8 Developer Previewclient.  At first I thought it was my download was corrrupted.   I didn’t have any problems with the Server version.

But then, after restarting my computer, I lost my “Bootmgr”.

Now, this happened because I boot to multiple OS’s: Windows Server 2008 R2 and Windows 7.  I had one successfull installation of the “Windows 8 Server Developer Preview” but on my Windows 7 the installation failed to install over.  The problem is, you will not notice your “BootMgr is missing” error after a reboot was performed.

So, what precautions you should take to prevent this issue:

  1. Make sure you have create a “System Repair Disk” for you Operating System.
  2. Also, do a Windows Backup.

In most cases, using the “System Repair Disk” will get you out of the hold.  In my situation, I had to delete all my System, and my Windows 7 Partition.  This way I took a longer route and able to put back a clean Windows 7 OS, and only then I could successfully install “Windows 8 Developer Preview” client.

Now,  looking back to what I had done, I realized that MAYBE I would have avoided this issue if I had paid attention to the Windows 7System Configuration“.  And, here’s why:

There’s a possibility the failed installation of the Windows 8 client was due to not having my Windows 7Set as Default” boot OS.   Now, if this doesn’t work, then delete the partitions and try again.

At the end, I finally got my BootMgr working with two OS’s: Windows 8 Server and Windows 8 Developer Preview working fine.

I’m ready!! To continue install applications, and doing more test with Windows 8.

To download Windows 8 Editions, go to your MSDN subscription, or get it at this link: http://msdn.microsoft.com/en-us/windows/home/

Happy Testing!!

Posted in Windows 8 | Comments Off

Yes! Windows 8 Editions with PowerShell V3 included

Tonight I was able to download both Windows 8 Server with Hyper-V and the Windows Developer Preview ISO.  I will create VM using the Developer Preview ISO, and then take a look at PowerShell V3 new cmdlets.  As, everyone got an early start downloading the Windows Developer Preview edition, I will be working on the server version.

As you already know by now, PowerShell V3 is here with lots of new command to help manage your computer system.  But, don’t take my word for it, if you’re at the BUILD Conference, don’t forget to attend Jeffrey Snover PowerShell Sessions: http://www.buildwindows.com/Sessions?q=PowerShell&x=0&y=0

There’s a possibility that Jeffrey’s BUILD sessions will be recorded and can be viewed later on the following address: http://channel9.msdn.com/Events/Speakers/jeffrey+snover

To download Windows 8 Server and/or Developer Preview editions, look in both your MSDN Subscription, and/or at the following link: http://msdn.microsoft.com/en-us/windows/home/

Windows 8 Server w/Hyper-V

The installation started with executing the downloaded *exe: en_windows_server_developer_preview_with_hyper-v_virtual_machine_x64_735222.exe

This executable will extract a VHD file:

Now, this VHD is good if you a media were you can boot from a thump-drive, or use the Windows 7 Boot from VHD feature.

Now, you’re better off downloading the ISO and burned it into a DVD.  So, look for the “Windows Server Developer Preview (x64) – DVD (English)” in your MSDN Subscription.

I lost my BootMgr!

Yeap! I was trying to use the Boot from VHD in Windows 7 but the documentation out there doesn’t tell you to activate the attached VHD and make it active to boot.  So, I try a couple fo things but to end up with “… Bootmrg is missing …” message.  Well, how can I resolved this new issue.  The answer was found in Microsoft Answer: “windows 7 bootmgr is missing– resolved using WinRE” – http://answers.microsoft.com/en-us/windows/forum/windows_7-system/windows-7-bootmgr-is-missing-resolved-using-winre/8bb148bc-8035-4847-9696-888f7a0a9720

So, I prepare a recovery DVD using the “Create a system repair disc” found in the “Backup and Restore” section.  It works like a charm!

Back to Windows Virtual Machnes

By the way, I did try to create Windows 8 VM’s in both Windows 2008 R2 Hyper-V and Windows 7 “Windows Virtual PC” but didn’t work.

Now, I’ve heard that it’s possible to create a Windows 8 VM using VirtualBox.  Try it!

On my laptop, I decided to install “Windows 8 Server w/Hyper-V” over my “Windows Server 2008 R2 SP1″.  This way I can start setting up my new VM’s and see how the my older ones work under this new OS.  This installation took about a couple of hours with a series of reboots.

Before, creating my VM’s, I needed to install the Hyper-V role and enable PowerShell ISE using the new Server Manager dashboard:

When you click on the Windows Flag to look for your application, it will take you to the new Start menu:

You will notice that “PowerShell” is available next to”Server Manager“.  We click on Powershell and enter the $PSVersionTable to check version:

As you can see, this is PowerShell Version 3.  This version comes with a total of 56 available Modules, 521 Cmdlets (excluding Modules command), 637 functions, and 146 Aliases.  You got plenty of learning opportunities with this new version.

Now, As you all know, under the server features you need to “enable” PowerShell ISE.  I try to use the Classic “Control Panel” but it didn’t work for me.  So, you need to use the Server Manager, and click on the Manager Menu to get to “Add Feature” option:

After you have selected both Role(s),and Feaures then you’re ready to install them:

When the installation is completed, you will find PowerShell ISE ready to use from the new START menu:

After having installed Hyper-V, I was able to create both 64bit version of Window 8 Server and Desktop.

Now, how do you Shutdown your Windows 8 Server?  Just do a Ctrl-Alt-Del and then at the “Shutdown” button found at the bottom right of the screen.

Let’s the fun begin!!

Big Hint!!  Just found this tweet about booting from VHD: “New Blog: How to Boot from VHD with Windows 8 Developer Preview: http://t.co/JIBBQze3

Additional Note:  The client version of Windows Developer Preview, altought PowerShell V3 is included, it doesn’t show in your Start Menu.

Posted in PowerShell, Windows 8 | Comments Off

Presenting at Orlando SQL Saturday #85: Extend your T-SQL Scripting w/PowerShell

Date: Saturday, September 24th – Session starts at: 2:45PM

Session Level: Intermediate

I’ll be covering some of the different way we can use PowerShell to extend our T-SQL scripting.  This session will include a mix of using SMO, .NET classes, and SQLPS to help you understand the power for new scripting technology.  At the end, we’ll be creating a solution that put together all this techniques.

See You all there!!

 

Posted in Uncategorized | Comments Off

No-Hassle SQL Server Remoting with PowerShell V2

Although, PowerShell give the whole remoting experience, you may still need to ask you network administrator to let you configure remoting on all the machines you need to access.  Of course, unless you hold the keys of the kingdom.  But, it is much  simpler without PowerShell Remoting.

When you use the SQLPS Module it automatically let you connect to any of your SQL Servers on your network.  So, YES!! As long as you have permission to manage these servers, SQLPS already gives you the ability to remotely connect to other machines.  There’s no need to setup the Remoting with  Enable-PSRemoting or Set-WSManQuickConfig commands.

Simple Remoting #1

So, How can I change from my SQL Server local prompt to another instance?  Here’s an example how:

1. First load the SQLPS Module:

Import-Module SQLPS -DisableNameChecking

2. Confirm you have the SQL Server drive available:

Get-PSDrive SQL*

3. Let’s navigate to your SQL Server Instance:

cd SQLServer:\SQL\Your-Machine-name\Default  #or

cd SQLServer:\SQL\Your-Machine-name\Your-InstanceName

4. Now you can continue and navigate through your SQL Server drive like in DOS filesystem.

Dir Databases -force

5. Finally, to remote connect top another session just change the “Your-Machine-name”, and your “Your-InstanceName”.

Simple Remoting #2

One thing you need to understand, after you load SQLPS module, now you have access to all SMO (SQLServer Management objects) .NET Classes. This will help you build short and very effective .NET that extend the scripting of PowerShell.  Also, you don’t need to be at the SQLServer: drive to use it.

Here’s a basic example using SMO:

1. First load the SQLPS Module:

Import-Module SQLPS

2. Create a variable to hold your local SQL Server objects:

$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server

3. Now that your .NET object has been create you need to see all what you can grab from it:

$MySQL | Get-member | Out-GridView

4. I decided to grab the “Information” property so I can display all the information, and verify that this is my local SQL instance:

$MySQL.Information

5. Finally, to remote connect to another machine, I just add the SQL Server InstanceName to the line creating my variable:

$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server "Your-Machine-name"

Or

$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server "Your-Machine-name\Your-Instancename"

Keep in mind, you can another variable holding your SQL Server name with the instancename and do something like:

$SQLInstanceName = "Your-Machine-name\InstanceName"
$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLInstanceName
$MySQL.Databases[$SourcedbName].tables | sort -desc dataspaceused | select Parent, `
 @{Label="DisplayName";Expression={$_.Schema+"."+$_.Name};} | `
 sort DisplayName;

Again, no need to setup PSRemoting.

Simple Remoting #3

And this is the simplest of all, if you like to reuse your T-SQL scripts.  This will be your most used PowerShell SQLPS cmdlet “Invoke-SQLcmd“.

1. Load the SQLPS module:

Import-Module SQLPS

2. Just start using the SQLPS “Invoke-SQLcmd” command: (basic form)

Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "."  #or

$SaveResult = Invoke-Sqlcmd -Query "SELECT * FROM [AdventureWorks].[dbo].[AWBuildVersion];" -ServerInstance "Your-Machine-name\InstanceName"

$SaveResult

Again, there’s no need to be at the SQLServer: drive in order for this to work.  As you can see, with just a few lines of code you can connect to another SQL Server instance.

Go ahead and try it!

Posted in PowerShell, SQL Server | Comments Off

Creating your own ExitCode in PowerShell and use it in SSIS package

As I started to build executable solutions in PowerShell for my SSIS packages, now I need to take advantage of providing an Exit Code value within the application.  Creating your own exit code can be very useful for providing a Success or Failure of a task.  This is way you can take the correct action on how your flow is going to behave.
I found a great blog article from one of my MVP college – MOW that got me started:
# http://thepowershellguy.com/blogs/posh/archive/2008/05/20/hey-powershell-guy-how-can-i-run-a-powershell-script-from-cmd-exe-and-return-an-errorlevel.aspx
Also, here’s an MSDN blog article: # http://msdn.microsoft.com/en-us/library/system.environment.exit(v=VS.80).aspx.  These article lead me to find multiple ways to introduce an Exit Code in PowerShell.
In its basic form:
1. Exit N – as shown on MOW’s blog (link above), only work in PowerShell
2. Exit (“N”) - I just try it but only work with PowerShell.
3. [Environment]::Exit(“N”) - Following the MSDN article (link above), it work in both PowerShell and DOS.
Here’s where “N” equals the Exit Number you want to provide.  Also, you need to understand that this only work when executing your script with the PowerShell.exe at any command prompt: DOS or PowerShell.
Now, as you notice and probably wondering, I found out that “Exit N” and Exit(“N”) behave differently when is executed in both as a script, and compiled under PrimalForms 2011.  I will show this in my examples.
In PowerShell V2, I found some different behaviour when using the above methods.  My goal in these exercise is to provide an Exit Code that can be use in either PowerShell (as a Script and as Executable) and DOS (as executable).  The reason is that you want to eventually convert your script as an executable in the future.
Here’s the basic structure on how this is done taking an example of a Division process where we’ll be trapping the “Divided by 0″ exception using “Try-Catch“.  Then, after testing our script we can create the executable that can be included in an SSIS solution.
To validate the Exit Code has a value, we need to create en executable using PrimalForms 2011, then use the $LastExitCode in PowerShell and the %ErrorLevel% in DOS to confirm we have the values we want.  Both Exit Code values need to match in PowerShell and DOS.  These samples scripts will run under PowerShell console, and the compiled *.exe version will run under DOS.
Sample Script 3 – DivideNow3.ps1 – using “Exit N”.
#========================================================================
# Created with: SAPIEN Technologies, Inc., PrimalForms 2011 v2.0.12
# Created on:   8/31/2011 6:33 PM
# Created by:   Max Trinidad
# Organization: PutItTogether
# Filename:      DivideNow3.ps1
# http://thepowershellguy.com/blogs/posh/archive/2008/05/20/hey-powershell-guy-how-can-i-run-a-powershell-script-from-cmd-exe-and-return-an-errorlevel.aspx
# http://msdn.microsoft.com/en-us/library/system.environment.aspx
#========================================================================
Param([Int] $arg1, [Int] $arg2)
Try
{
	[Double] $result = $arg1 / $arg2;
}
Catch
{
	#Write-Host "Error in function";
	$err1 = 1;
}
Finally
{
	if($err1 -eq 1)
	{
		## - Custom Exit Code:
		Exit 99;
	}
	Else
	{
		Write-Output $result;
		Exit 0;
	}
}
Results for DivideNow3.ps1
Sample Script 2 – DivideNow2.ps1 – using “Exit(“N”).

#========================================================================
# Created with: SAPIEN Technologies, Inc., PrimalForms 2011 v2.0.12
# Created on:   8/31/2011 6:33 PM
# Created by:   Max Trinidad
# Organization: PutItTogether
# Filename:      DivideNow2.ps1
# http://thepowershellguy.com/blogs/posh/archive/2008/05/20/hey-powershell-guy-how-can-i-run-a-powershell-script-from-cmd-exe-and-return-an-errorlevel.aspx
# http://msdn.microsoft.com/en-us/library/system.environment.aspx
#========================================================================
Param([Int] $arg1, [Int] $arg2)
Try
{
	[Double] $result = $arg1 / $arg2;
}
Catch
{
	#Write-Host "Error in function";
	$err1 = 1;
}
Finally
{
	if($err1 -eq 1)
	{
		## - Custom Exit Code:
		Exit("99");
	}
	Else
	{
		Write-Output $result;
		Exit("0");
	}
}
Results for DivideNow2.ps1
Sample Script 1 – DivideNow.ps1 – using .NET “[Environment]::Exit(“N”)”.

# Organization: PutItTogether
# Filename:      DivideNow.ps1
# http://thepowershellguy.com/blogs/posh/archive/2008/05/20/hey-powershell-guy-how-can-i-run-a-powershell-script-from-cmd-exe-and-return-an-errorlevel.aspx
# http://msdn.microsoft.com/en-us/library/system.environment.aspx
#========================================================================
Param([Int] $arg1, [Int] $arg2)
Try
{
	[Double] $result = $arg1 / $arg2;
}
Catch
{
	#Write-Host "Error in function";
	$err1 = 1;
}
Finally
{
	if($err1 -eq 1)
	{
		## - Custom Exit Code:
		[Environment]::Exit("99");
	}
	Else
	{
		Write-Output $result;
		[Environment]::Exit("0");
	}
}

Results for DivideNow.ps1

This is the results we want to get.  Both DOS and PowerShell will show the correct assigned Exit Codes.  This script and executable will work and can be integrated in an SSIS package.
Bonus Script – Executing a PS Script from PowerShell.exe in the PowerShell Console to execute DivideNow.ps1
#========================================================================
# Created with: SAPIEN Technologies, Inc., PrimalForms 2011 v2.0.12
# Created on:   9/2/2011 9:21 AM
# Created by:   Max Trinidad
# Organization: PutItTogether
# Filename: DivideNow_test.ps1
#========================================================================

# .\DivideNow.ps1 40 5  - This will execute and close PowerShell immediately
# .\DivideNow.ps1 40 0  - This will execute and close PowerShell immediately

# But if I execute with PowerShell.exe
PowerShell -noexit -command { `
	cd 'C:\Users\Max\Documents\SAPIEN\PrimalForms 2011\Files'; `
	& ./DivideNow.ps1 40 5}

$LastExitCode

PowerShell -noexit -command { `
	cd 'C:\Users\Max\Documents\SAPIEN\PrimalForms 2011\Files'; `
	& ./DivideNow.ps1 40 0}

$LastExitCode
Happy PowerShelling
Posted in PowerShell, SQL Server | Comments Off

Passing Parameter to a PowerShell executable – Part 2

Using a PowerShell executable w/Param() in SSIS

Here’s where the fun begins.  It took me a few hours to figure something out in order to my SSIS package pass some values into my PowerShell executable.  So, here’s a sample solution where I found out that my Flat file source record didn’t match the record layout provide by another Internet source.  Yes, believe or not, sometimes documentation out there might be way out of day.  But, Thanks to SSIS “..Source Error Output“, you can redirect these records error to a destination object.  Then you can later analysis these bad records.

So, if you work creating SSIS packages, then everyone should know how to use the “Data Flow component” to help you define your data Source, and Destination objects.  Now, in cases when you need to isolate records that are causing your package to fail, then you need to add a second Destination object to deal with them later.  In my example, my second Destination object will be to a new SQL table called “CompanyData_SkippedRecords“.

Here’smy sample Text file to be process by my SSIS package: “CompanyData.txt”

Sample Dummy CompanyData.txt Source file

Notice, the first line are the columns, but some of the data in this file won’t match the column layout.    If I run this solution with the Source and Destination objects defined, this package will fail.

Unmatching records causing SSIS package to fail

Now, we can add your another Destination component to isolate these unmatching records.  Connect the Source component by dragging the “Red Arrow” to the second Destination Component handling the errors.

Dragging the RedArrow from Source to the second Destination Component

A “Configure Error Output” windows will popup, change the “Set this value to selected cells:” to  “Redirect row“.  Then, highlight all fields in both “Error” and “Truncation” columns, and Click “Apply” to change the “Fail Component” to “Redirect row“.

Change both "Error" and "Truncation" to "Redirect Row"

Click “OK” when you confirmed that all fields has “Redirect row“.

Verify all fields has "Redirected row"

These changes are in place for our Flat File Source “Error Output” section.

Now, we need to complete setting up out second destination component labeled “Error Skipped Records Destination” where our Error Records will be dropped into our new SQL table.

Open our Error Destination component.  For now, we are going to use the default, the new table will be named “[Error Skipped Records Destination]“.  So, all bad records will be stored in this table.

Accept Default Error table name

Then, click “OK” to exit.

At this step we are done with our Import and Error/Mismatch records handling, and we are ready to run our solution.  At the end of this step will have bad records table.

4 bad Record went into our Err table

Here’s our good data:

And, this is Error Records table:

Now, the next step, I need to a table to consolidate all my mismatched records.  I will be reading from my “[Error Skipped Records Destination]” and selecting the “[Flat File Source Error Output Column]” field as “DataSkipped” into a new table called “CompanyData_SkippedRecords“.

Here’s the new table layout:

USE [Developer]
GO

/****** Object:  Table [dbo].[CompanyData_SkippedRecords]
Script Date: 08/18/2011 12:27:15
*****/

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[CompanyData_SkippedRecords](
	[DataSkipped] 1 NOT NULL,
	[ErrRecordsLength] [varchar](7) NOT NULL,
	[TotalFieldsPerRecords] [varchar](5) NOT NULL,
	[FileGroupSource] [varchar](4) NOT NULL,
	[ProcessDate] [datetime] NOT NULL,
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

As you may notice, this table is very different than the we one createdto store the errors.  And here’s where we integrate our PowerShell script solution into our SSIS Package.

PowerShell Script

In this new table out of the 5 fields 4  will be genrated by PowerShell , and two of them are coming from parameters:

  1. DataSkipped – comes from the our Err table.
  2. ErrRecordsLength – Count of the length of each records skipped.
  3. TotalFieldsPerRecords – Count the number of fields per records (using the delimiter -1).
  4. FileGroupSource – Denominates the type of records that was imported (ie.Comp).
  5. ProcessDate – Date that this Err table was process.

The purpose of this PowerShell executable it to generate this additional fields to help analyzing what’s wrong with my Text file.  This process will read one Err Record at a time, generate the addition values, and insert into the new table.

One requirement: You need to have the SQLPS module installed in your “MyDocument\WindowsPowerShell\Modules” folder were the user is running this SSIS package, or will not run. If you’re usign SQL Server 2008 R2, then download the SQLPS module from Chad’s Miller blogsite:http://sev17.com/2010/07/making-a-sqlps-module/(SQL Denali CTP3 already has it). max

Here’s the Script (don’t be scare!), to be compiled with PrimalForms 2011:

# =============================================================
# Microsoft PowerShell Source File -- Created with SAPIEN Technologies PrimalScript 2011
# NAME: AnalyzeSkippedRecords.ps1
# AUTHOR: Max.Trinidad ,
# DATE  : 8/18/2011
#
# COMMENT: PowerShell Script to Analyze the Data Skipped for processing and update the Skipped
# table with additional information.
# =============================================================
PARAM([String] $Arg1, [String] $Arg2, [String] $Arg3)
#Imput: $Arg1="Err*"; $Arg2 = "Developer"; $Arg3 = "YourComputer"

Import-Module SQLPS -DisableNameChecking;

[DateTime] $ProcessDate = (get-date).month.ToString("00")+"/"+(get-date).Day.ToString("00")`
	+"/"+(get-date).Year.ToString()

$MySQL = new-object('Microsoft.SqlServer.Management.Smo.Server') $Arg3
$SchemaTableList = $MySQL.Databases[$Arg2].tables | where {$_.name -like $Arg1} | `
  select @{Label="Schema_Tablename";Expression={$_.Schema+".["+$_.Name+"]"};};

foreach($table in $SchemaTableList)
{
	$tblName = $table.Schema_TableName;

$sqlqry1 = @"
USE $Arg2
GO

select
	[Flat File Source Error Output Column] as DataSkipped
  from $tblName
"@;

	$rdSkipData = Invoke-Sqlcmd -ServerInstance $Arg3 -Query $sqlqry1;

	$recCount = 0;
	Do
	{
		$getInfo = $rdSkipData[$recCount] | select DataSkipped., `
			@{Label="ErrRecordslength";Expression={($_.DataSkipped).Length};}, `
			@{Label="TotalFieldsPerRecord";Expression={(($_.DataSkipped).split("^")).count};};

		$DataSkipped = $rdSkipData[$recCount].DataSkipped.ToString().Replace("'","").Replace('"','').Trim();
		$ErrRecordsLength = $getInfo.ErrRecordsLength;
		$TotalFieldsPerRecord = $getInfo.TotalFieldsPerRecord;
		$FileGroupSource = $Arg1;

$sqlqry2 = @"
USE $Arg2
GO

INSERT INTO [dbo].[CompanyData_SkippedRecords]
VALUES(
	'$DataSkipped'
	,'$ErrRecordsLength'
	,'$TotalFieldsPerRecord'
	,'$FileGroupSource'
	,'$ProcessDate'
)
GO
"@;
Write-Host $sqlqry2

		Invoke-Sqlcmd -ServerInstance $Arg3 -Query $sqlqry2;
		$recCount++
	} Until($recCount -eq $rdSkipData.Count);
}

Notice this script was meant to search for multiple error tables based of the type of File groups (ie. ADB1, ADB2, and ADB*).  Now, using the steps from Passing Parameter to a PowerShell executable – Part – 1 on the previous blog, i compiled my script and create my executable.  Keep in mind, the you will need to move this executable to the machine you are running this SSIS Package.  Thanks to SAPIEN for this Great product!

Create SSIS Variables for input Parameters for the PowerShell Executable

This part took me a few hour to figure out how to pass parameters using the SSIS variables in combination with “Expressions”.  Yes!!  That was the keyword “Expressions”.  I couldn’t fine a blog out there that will properly explain this process.  Just one that I will give some credit because this keyword got my attention: http://dennyglee.com/2006/05/12/ssis-global-variables-and-execute-process-task/ – “..you can modify the Execute Process Task at the point of the Property Expression attribute..”.  Unfortunately, thsi blog didn’t show a step-by-step on how this done.  But, lucky you, I’m blogging about it.

Here’s how is done:

Create three variable that will hold some parameters values to be injected into the executable:

Create variable to be use as parameters to our PowerShell executable

Now, we add the “Execute Process Task” component, connect the “Data Flow Task”, and double-click on the “Execute Process Task”.  In the “Execute Process Task Editor”, go to the “Process” section and in “Executable” add the executable name “AnalyzeSkippedRecords.exe”.

And now,… to setup your input parameters,  Go to the “Expressions” section:

Property Expression Editor - Select Arguments

Here’s where you define the input Argument(s) for your executable(s).  Under “Property expressions”, you select the property “Argument”, and then click on the “…” to build the expresions:

Building your Input Arguments

Yes!! This is the money maker:  ( there’s a space between the double-quotes )

@[User::ErrorGroup] + ” ” + @[User::SourceDatabase] + ” ” + @[User::SQLInstance]

Now, click “OK” twice to save the changes, and  we ready to run our full SSIS package.

Success!! This solution works.

Check my “CompanyData_SkippedRecords” table:

Checking my Skipped data

Now, I can keep working on analyzing this data with PowerShell, and/or other tools.

Couple of Pointers:

In the “Execute Process Task Editor”, you can troubleshoot your executable session if you leave the setting “WindowStyle” to Normal.  This way you can see the console popup. Then, when everything is working correctly, change it back to Hidden“.

Also, if you’re having some problem with the PowerShell executable failing, you can add the “Write-Host ‘Pause’; Start-Sleep -second 10;” oneliner command to pause the session and give you time to see the error when leaving the “WindowsStyle” as Normal.

Download this SSIS_PowerShell_sample solution at:

Posted in PowerShell, SQL Server | Comments Off

Passing Parameter to a PowerShell executable – Part 1

Creating a PowerShell Executable with Parameter(s)

Recently, I’ve been creating some PowerShell script, and intergrating it into my SSIS solution.  You may ask, but how??  Simple, if you a product such as SAPIEN’s PrimalForms (or, PrimalScript), you can create an executable out of your script.  Yes!! You can create an executable file of your PowerShell script.  But, not until recently, I didn’t need to pass parameter(s) my  compiled version of my script(s).

Let’s start with some very basic sample of how you create a PowerShell executable script that will accept parameters and display the results on the PowerShell Console prompt.

First the Sample Script, my of “HelloWorld” executable -”HelloWorldExec.ps1″

#========================================================================
# Created with: SAPIEN Technologies, Inc., PrimalForms 2011 v2.0.9
# Created on:   8/17/2011 6:08 PM
# Created by:   Max Trinidad
# Organization:  ISO Group, Inc.
# Filename:      HelloWorldExec.ps1
#========================================================================

Param([string] $firstName, [string] $lastName)
Write-Host "Hello Work!! I'm $firstName $lastName" `
    -BackgroundColor Black -ForegroundColor Yellow

#end of script

Now, we need to compiled this script using “Script Packager” under the “Export” tab in PrimalForms 2011.

Open 'Package File"

We are going to select to build the executable for a “WIN32 Command Line” because this script is consider a Console Application and there’s no windows form in it. We click in the “Build” button to cerate the EXE. This exe file will be built in the same folder where your script are stored.

Make sure to select WIN32 or WIN64 Command line option

Let’s open my PowerShell Console, change directory to where my executable is located, and run it.  Test the executable in both DOS and PowerShell command prompt:

Testing PowerShell executable in both DOS & PowerShell Console

Good!  As you can see this is a very simple script.  Basically, this script doesn’t need to be a function in order to use the Param() keyword to accept two input arguments: $firstName, and $lastName.

Now, we are ready to build another executable so we can use it on our next blog Part-2PowerShell Integration to a SSIS solution“.

For more information about SAPIEN’s PrimalForms 2011, click on the link:  http://www.sapien.com/software/primalforms

Posted in PowerShell | Comments Off

Great SQL Saturday South Florida Event – PowerShell included!!

Yes!!  It was a great event with over 400 people showing up, and only two PowerShell Sessions included.  Thanks to all SQL Saturday organizers for all the efforts in putting this events together.  I’m honor to be part of it.  Thanks Scott and Herve!!

Well, here’s both presentations: Session 1 – Let’s Talk About SQL PowerShell, Session 2 – Extendign your T-SQL with PowerShell, and more samples:

Many THANKS!! to all who attended my sessions, and I know that you all were asking for more at the end.  This is just an example that there’s a lot to talk about PowerShell and every little time to do it.  But, don’t worry!

I’m in the process of setting up some livemeeting event every on the third week of the month at 11:30am(EST).  It will a “PowerShell Code Snippet” 3o minutes demo with the purpose of showing block of code by myself and our PowerShell community.  Hopefully, this will speed up your learning by reusing these block of code.

Stay Tuned to this blog site for more information.

Just forgot… Congrats to all the winners how found marking on the flyers I provided.  I gaveaway 2 SAPIEN PowerShell V2 ebooks (X), 2 PluralSight One Month Training  Subscription(PL), and 2 Diskeeper Pro Premier Defrag software for desktop (D).

Happy PowerShelling!!

Posted in Events, PowerShell, SQL Server | Comments Off