So a colleague asked me for some help with a manual task he was performing daily; extract the results of an SQL query to a CSV file and drop it on a file share of another system for billing purposes.
Let me set the stage for you first. Our network is segregated so putting the extracted results on a file share for the billing system is not going to be easy.
- SQL Server 2008 R2 is our RDBMS
- Windows 2008 R2 64bit is the OS
- Powershell is my tool of choice with a splash of .Net (in this case 3.5)
- SQL Server Management Studio (cuz I need the snap-in goodness)
Of course I needed some help to the interweb and articles on the following:
- Encrypting SQL passwords using PS; http://bit.ly/1dBFoYY
- Learning a little about Invoke-Sqlcmd; http://bit.ly/1g8pVtQ
- More PS and Invoke-Sqlcmd; http://bit.ly/1pC29vT
Now I was ready all my tools and requirements in place to put this thing together, to solve the problem regarding the share I was going to employ email as my vehicle for delivery.
My 'solution' uses three (3) scripts; the main script to execute the query to a file which utilizes a second script file as a library to decrypt my username and password. The final script is the one I do not put on the server but use to generate my password file but also uses the second script file as a library to encrypt the values.
** Something I learned is that if you are using passwords with special characters the cryptography algorithm truncates the passed in value!! You need to therefore use an escape character in your password to prevent this from happening.
Above I mentioned the snap-in goodness where here is where it comes in handy, the snap-in allows me to run my query in a single line being as efficient as I can with my code focusing on the things that matter; the query and delivery of results.
In the main script adding a little logging (stringbuilder) and error handling for good measure and I was done. I hope you found this helpful, I enjoyed putting this together and really enjoy using Powershell.