Click here to Skip to main content
Click here to Skip to main content

A Quick Guideline for Microsoft Windows PowerShell: Part 3

By , 21 Aug 2010
 

Table of Contents

Introduction

Microsoft Windows PowerShell allow us to work with the Microsoft Office System APIs. For example, Microsoft Office 12.0 Object Library. Before I start, I would like to request you to read:

***If you read part-1 and part-2 from the above links, then I think it will help you to understand the current scenario, what we are actually doing in this section.

However, the objective of this article (Part 3) is to introduce you to Microsoft Windows PowerShell and learn some basic commands of windows PowerShell. We will also try to work with various objects; we will work with Microsoft Office System, XML document, Microsoft SQL server and some other stuff as well.

How to Work with Objects

Every action you take in PowerShell is done within the context of object. We can create an instance of a COM object. To create an instance of a COM object, we use the ComObject parameter and specify the ProgID of the object as its value.

Syntax
New-Object [-typeName] <string> [[-argumentList] <[Object]>] [<CommonParameters>]
New-Object [-comObject] <string> [-strict] [<CommonParameters>]

For example, we want to write a PowerShell script which will open the browser and navigate to a custom / users defined URL (http://www.codeproject.com/). So, how can we achieve this? For doing that, our script will be like:

$objBrowser = New-Object -comobject InternetExplorer.Application 
$objBrowser.navigate2("http://www.codeproject.com/")
$objBrowser.visible = $true

Microsoft Windows PowerShell & Microsoft Office System

Well, I hope that you dig up some basics of windows PowerShell. So let’s start...
In this section, we will learn how to create an instance of an Object. We will write some scripts for Microsoft Office System & work with some other APIs as well.

PowerShell Script for Microsoft Word

Now let’s try to have some fun, our requirement is to read the content from a Microsoft Office Word document file, manipulate the content of that document and finally save the document. For doing this; the Windows PowerShell script will be like:

$objWord = New-Object -Com Word.Application
$objWord.Visible = $true
$objMissingValue = [System.Reflection.Missing]::Value

$objDocument = $objWord.Documents.Add($objMissingValue, _
	$objMissingValue, $objMissingValue, $objMissingValue)
$objParaHeader = $objDocument.Paragraphs.Add($objMissingValue)
$objParaHeader.Range.Style = "Heading 1"
$objParaHeader.Range.Text = "The power of Microsoft Windows PowerShell"
$objParaHeader.Range.InsertParagraphAfter()

$objParaText = $objDocument.Paragraphs.Add($objMissingValue)
$objParaText.Range.Text = "I will not say I have failed 1000 times; _
   I will say that I have discovered 1000 ways that can cause failure – Thomas Edison."
$objParaText.Range.InsertParagraphAfter()

$filename = 'C:\Script\PowerShell-Example.doc'
$objDocument.SaveAs($filename,
$objMissingValue, $objMissingValue,
$objMissingValue, $objMissingValue,
$objMissingValue, $objMissingValue,
$objMissingValue, $objMissingValue,
$objMissingValue, $objMissingValue)

##Once the script has added all of the required content the document should be closed:
$objDocument.Close()
$objWord.Quit()

PowerShell Script for Microsoft Excel

Now let’s try to have some fun with Microsoft Excel, our requirement is to read the content from a Microsoft Office Excel spreadsheet and display the content as well. For doing this; the Windows PowerShell script will be like:

$objOleDbConnection = New-Object "System.Data.OleDb.OleDbConnection"
$objOleDbCommand = New-Object "System.Data.OleDb.OleDbCommand"
$objOleDbAdapter = New-Object "System.Data.OleDb.OleDbDataAdapter"
$objDataTable = New-Object "System.Data.DataTable"

$objOleDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;_
 Data Source=C:\Script\PowerShell-Example.xls;Extended Properties=""Excel 8.0;HDR=YES"""
$objOleDbConnection.Open()

$objOleDbConnection.State

$objOleDbCommand.Connection = $objOleDbConnection
$objOleDbCommand.CommandText = "SELECT * FROM [Sheet1$]"

##set the Adapter object
$objOleDbAdapter.SelectCommand = $objOleDbCommand

##fill the objDataTable object with the results
$objOleDbAdapter.Fill($objDataTable)

##To display the “raw” contents, just enter
$objDataTable

##show the first line 
$objDataTable.Rows[0].Name

## close the connection 
$objOleDbConnection.Close() 

The figure below is the output of the above script:

Excell.png

PowerShell Script for Microsoft Access

For now, our requirement is to read the content of a table from a Microsoft Office Access database and display the content as well. For doing this; the Windows PowerShell script will be like:

$objOleDbConnection = New-Object "System.Data.OleDb.OleDbConnection"
$objOleDbCommand = New-Object "System.Data.OleDb.OleDbCommand"
$objOleDbAdapter = New-Object "System.Data.OleDb.OleDbDataAdapter"
$objDataTable = New-Object "System.Data.DataTable"

$objOleDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;_
	Data Source=C:\Script\PowerShell-Example.mdb;"
$objOleDbConnection.Open()

$objOleDbConnection.State

$objOleDbCommand.Connection = $objOleDbConnection
$objOleDbCommand.CommandText = "SELECT * FROM [Example]"

##set the Adapter object
$objOleDbAdapter.SelectCommand = $objOleDbCommand

##fill the objDataTable object with the results
$objOleDbAdapter.Fill($objDataTable)

##To display the “raw” contents, just enter
$objDataTable

## close the connection 
$objOleDbConnection.Close() 

The figure below is the output of the above script:

AccessDB.png

Microsoft Windows PowerShell & Microsoft SQL Server

We can use PowerShell script for several purposes. For now, our requirement is to read the contents of a table from a Microsoft SQL Server database, display the contents and finally export the data into a CSV file as well. For doing this; the Windows PowerShell script will be like:

#Connection Strings
$Database = "Northwind"
$Server = "localhost"
#Export File
$fileName = "C:\Script\SQLData.csv"
# Connect to SQL and query data, extract data to SQL Adapter
$SqlQuery = "SELECT TOP 100 *  FROM [Northwind].[dbo].[Orders]"
$objSqlConnection = New-Object System.Data.SqlClient.SqlConnection
$objSqlConnection.ConnectionString = "Data Source=$Server;_
	Initial Catalog=$Database;Integrated Security = True"
$objSqlCommand = New-Object System.Data.SqlClient.SqlCommand
$objSqlCommand.CommandText = $SqlQuery
$objSqlCommand.Connection = $objSqlConnection
$objSqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$objSqlAdapter.SelectCommand = $objSqlCommand
$DataSet = New-Object System.Data.DataSet
$objSqlAdapter.Fill($DataSet)
#Populate Hash Table
$objTable = $DataSet.Tables[0]
$objTable | Export-CSV $fileName

$objTable 

Conclusion

I hope that this might be helpful to you. Enjoy!

Reference

  • Microsoft Development Network

History

  • 19th August, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Md. Marufuzzaman
CEO
Bangladesh Bangladesh
Member
He is the founder & CEO of MNH Technologies and working for urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc. He has over ten years of professional experiences in design and developing Client-Server, Multi-Tier, Database, Web based business software solutions, Enterprise Applications, API, WebAPI, Google Analytics implementation, Add-In, Documentation & Technical Writing etc for Windows / Mac using Microsoft SQL Server, Oracle, MySql, PS, C#, VB.NET, ASP.NET, PHP, RoR, Visual Basic etc. He has also more than two years experience in Mobile-VAS (Platform Development).
 
He worked for various software development & technology consulting. His core focus on technologies to create dynamic data-driven systems that add value to your business and dynamic technology consulting that builds advanced solutions for the industries across the various vertices.
 
He also work as a Solution Architect at Dhrupadi Techno Consortium Limited (DTCL) and responsible for analyzing business requirements and offered optimum solutions (multiple options), which would address all current requirements, provide flexibility for future growth and allow smooth transition between old system and new system.
 
He graduated with honors from The University of Asia Pacific, in Computer Science and Engineering. He was awarded as “Most Valuable Professional” (MVP) at 2010 and 2011 by CodeProject.com and also selected as a Mentor of CodeProject.com
 
Specialties: Software Development Management, System Integration, Data Warehouse Architecture, Virtualization.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberMohammad A Rahman11 Feb '12 - 12:18 
well written Smile | :)
GeneralIntegrating the word script with the sql server scriptmembersqlDude17019 Feb '11 - 5:16 
Awesome article. Very informative. How would you export the sql data to a word document instead of a csv file?
GeneralRe: Integrating the word script with the sql server scriptmvpMd. Marufuzzaman19 Feb '11 - 17:22 
Thanks for spend time on my post, anyways it just about fetch recordset and dump into ward doc.
I would request you to read once again section Data to a word document
You can also try the link below for some more scenario :
http://stackoverflow.com/questions/2277960/simple-fast-sql-queries-for-flat-files
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralMy vote of 5memberMohsiul Haque2 Nov '10 - 2:46 
good work
GeneralMy vote of 5memberTanvir Hasan Turan19 Sep '10 - 23:25 
Nice post.
GeneralExcellentmemberTaslima Bagum22 Aug '10 - 5:12 
Excellent post...Thumbs Up | :thumbsup:
GeneralRe: ExcellentmvpMd. Marufuzzaman22 Aug '10 - 18:04 
Thanks..
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralMy vote of 5memberaddy200520 Aug '10 - 4:43 
It helped me to get started with PowerShell
GeneralRe: My vote of 5mvpMd. Marufuzzaman20 Aug '10 - 7:09 
Gr8 & Thanks
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralGreat!memberaddy200519 Aug '10 - 2:07 
Hi Md! Those are really great articles. It's being a long time that i was trying to get started with PowerShell. Your articles just give me the opportunity to dig into it. Thanks a lot!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 21 Aug 2010
Article Copyright 2010 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid