Back in October 2014, I presented and recorded on my topic about working with Excel and PowerShell. I thought this video was lost but I founded it on a backup drive. Well its loaded with good samples using my favorite tool: SAPIEN’s PowerShell Studio. These tools are an essential for building .NET scripting and applications with PowerShell.
I recently helped someone with providing a solution using PowerShell to extract data from SQL Server into an Excel file. We all know that we could use SSIS to provide the means to do this but there are some situations you may want to use scripting instead. So, found one script I did back in 2009 that will do such a thing. The funny thing is, when I looked at it, I realized that for the Excel part I had a lot of unnecessary extra code and it could be improved greatly. So, here’s the updated version.
This *script will do the following steps:
1. Connect to SQL Server and get the SQL Server data.
2. Build the Excel file with columns heading and data.
3. Save the Excel file and Close/Terminate Excel process.
*Note: This script is PowerShell Version 2.0 compatible.
Getting you SQL Data
This script uses the ‘System.Data.SqlClient.SqlConnection’ which you can run on any machines without SQL Server installed. In this example the connection string is a trusted ‘Windows Authentication’. Then, I’m using the Here-String @”..”@ to insert the T-SQL script I want to execute against SQL Server. Keep in mind, this connection string can be change to use SQL Server Authentication.
[sourcecode language=”powershell”]
## ———- Working with SQL Server ———- ##
## – Get SQL Server Table data:
$SQLServer = ‘SQLServer01\MSSQLInstance01’;
$Database = ‘Database1′;
$SqlQuery = @’
Select top 10
[Field1]
,[Field2]
,[Field3]
,[Field4]
,[Field5]
from Database1.dbo.Table1
where [Field4] = ‘X001’
‘@;
## – Connect to SQL Server using non-SMO class ‘System.Data’:
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = `
"Server = $SQLServer; Database = $Database; Integrated Security = True";
## – Extract and build the SQL data object ‘$DataSetTable’:
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];
[/sourcecode]
Buidling the Excel file
This block of code will generate the Excel file consuming the SQL data object ‘$DataSetTable’. The result of the SQL DataSet will be use to automatically create the columns heading and data rows. This is the heart of the script where the magic happen.
[sourcecode language=”powershell”]
## ———- Working with Excel ———- ##
## – Adding the data start in row 2 column 1:
[Int] $rowData = 2;
[Int] $colData = 1;
foreach ($rec in $DataSetTable.Rows)
{
foreach ($Coln in $getColumnNames)
{
## – Next line convert cell to be text only:
$xlsSh.Cells.NumberFormat = "@";
## – Adjusting columns in the Excel sheet:
$xlsRng = $xlsSH.usedRange;
$xlsRng.EntireColumn.AutoFit();
[/sourcecode]
Saving and Terminating Excel
Now that I’ve build the Excel sheet, I need to save the file, quit and terminate Excel. And, Yes! It’s needed to terminate/kill the Excel process because this process will remain active even if when exiting/closing the PowerShell session.
One thing to understand, this process will work with small datasets. So, the more data you extract the slower it may take to build the Excel file. This is why is important to test the script(s) and look at other best possible solution. Maybe it’s better to use SSIS (SQL
Server Integration Services) but it doesn’t hurt try other technologies.
Here’s a quick way to start getting a list of SQL Server users having “SysAdmin” Role. Basically, I’m using SQLPS module (now available with SQL Server 2012) which loads all the SMO needed to help you script against your SQL engine.
This script does the following:
Import the SQLPS Module.
Connect to a SQL Server Instance.
Get the SQL Logins information.
Search for SQL users with “SysAdmin” Role, and builds a customized information in a PSObject.
Export the information to a CSV file.
Open the CSV file, which by default could open an Excel application(if installed on machine).
$SysAdmins | Export-Csv -Path ‘C:\temp\SQLSysAdminList.csv’ -Force -NoTypeInformation;
ii ‘C:\temp\SQLSysAdminList.csv’;
[/sourcecode]
Eventually, you could make changes to this scritp to be capable to access a list of SQL Servers and build your custom report.
Bonus:
To add the functionallity to connect to multiple servers, we can add a list of Servers and then using the “Foreach” statement to loop through the list, and with little changes to the previous code.
Here’s how it will look with just adding a few more line of code:
[sourcecode language=”powershell”]
## – Loads SQL Powerhell SMO and commands:
Import-Module SQLPS -disablenamechecking
## – BUild list of Servers manually (this builds an array list):
$SQLServers = "Server01","Server01\InstanceNameA","Server03";
$SysAdmins = $null;
foreach($SQLSvr in $SQLServers)
{
I have to admit that having setup Office 365 was a breeze. Just make sure you have a reliable fast internet connection, and you are good to go. By the way… no servers equipment is needed.
and
Well, since I got Office 365 Beta setup in my computer I’ve been looking for information about how to use PowerShell. Now, thanks to one of my PowerShell MVP
college (Sean Kearney) mention about this information been well documented in
Office 365 Beta. I found it, and I couldn’t believe it was that SIMPLE!!! YES,
SIMPLE!!
My computer environment is very basic. I have no Exchange, Linc, or Sharepoint. So now I’m part of the cloud experience with Office 365, and my answer of using PowerShell was at my fingertip.
If you want to try it, then check out the links below, and copy/paste the code. Make sure you meet all the requirements needed so you can experience using PowerShell with Office 365. By the way, It’s highly recommended by our PowerShell MVP’s colleges to set your Execution Policy to “ RemoteSigned” and not “unrestrincted”. Using “unrestricted” will still give you some security warning.
Office 365 – PowerShell – Resource Information Currently
available under: “Outlook Web App Help”
**You need to understand one thing, and quote this from the
help “… By default, all new user accounts are allowed to use Windows Remote Management (WinRM) to access the cloud-based organization with Windows PowerShell …”. But, the help documentation gives you the
code to prevent users to access remoting with Office 365. (read the help documentation)
By the way, there’s a recent change to the connection URI:
I love our PowerShell MVP Community. Here’s an observation from Aleksandar Nikolic: “… i think you should use generic Connectionuri(https://ps.outlook.com/powershell) and not specific server. you’ll be redirected … office365 will redirect you to closest, the least busy server …”. Thanks Alek.:)
This is totally true, and the only reason I included the change was to avoid the redirection warning message. So you can still use what’s documented:
We are pleased to announce the first South Florida IT Camp on Saturday, July 23rd 2011 from 8:00 am to 5:00 pm at Nova Southeastern in Fort Lauderdale.
Parking and admittance to this event is free. Lunch will provided. Please Register now. Let your friends and colleagues know about this event.
Join system administrators IT professionals and database professionals in addition to managers at all levels in Florida that work with Microsoft technologies for a “IT Camp Saturday”. IT Camps are a free, one day learning event for anyone seeking professional development. This event serves IT professionals and students with a focus on IT Pro related technologies. IT Camps offer a conference style learning environment free of charge to attendees and is open to presenters of
all backgrounds and expertise.
The call for speakers is open until 6/11. Topics can be anything applicable to System admins, and/or IT Pros including SharePoint, System Center, SQL Server, PowerShell, Active Directory, or Windows 2008 R2 and Windows 7.
To submit your session, please Click Here, or if you have questions? Comment or contact us.