Click here to Skip to main content
15,895,142 members
Articles / Database Development / SQL Server / SQL Server 2008
Article

Powershell How-To - Part 1

Rate me:
Please Sign up or sign in to vote.
2.50/5 (4 votes)
15 Dec 2008CPOL3 min read 22.4K   19   3
This article is a part of a series of articles that shows HOW-TO do various tasks in powershell.

Introduction

I was excited hear about powershell feature in SQL server 2008. Initially, it was not clear to me what it was, yet, I was enthused about learning something new. I imagined power shell would involve something in the command line. What happens after that was a complete mystery to me. Anyways, I managed to spend some extra time to learn about the powershell technology. I am going to split this article into multiple series. In the 1st part, I will cover how to work with variables and various helpful commandlets. The examples in this article assumes SQL server 2008, and windows powershell 1.0 is present. 

Background


Powershell is an extended shell that allows us to manipulate objects and do various scripting tasks. It takes the adavantage of .NET. We will often run into CmdLet in powershell. A commandlet is a .NET object that exposes functionalities for us. For example, there is a cmdlet called "New-Variable" which can be used to declare variables. 

Using the code

To start running powershell type in "sqlps" in command line prompt. If you do not know what cmdlets are available for use then simply type in "get-alias". This handy little cmdlet can show you the shorthand for the available cmdlet. This will get you started so you can start exploring cmdlets. There is another cmdlet named "get-command" that lists all available cmdlets.

PS SQLSERVER:\> get-alias

CommandType     Name            Definition
-----------     ----            ----------
Alias           ac              Add-Content
Alias           asnp            Add-PSSnapin
Alias           clc             Clear-Content 

When I started working with powershell, I struggled to find documentation on cmdlet. I looked in books online and it did not have much at that time. Only some references were there related to cmd-lets. Anyways, there is no need to despair. A cmdlet called "Get-Help" that can help you pull cmdlet related documentation from the command line. You need to supply the name of the cmdlet as the argument. Other useful arguments available for most cmdlets include "-detailed", "-full". Those flags allows you to bring additional information on the parameter. Amongst the, the "-full" flag is the most comprehensive. Also, if you type in "Get-Help *" then you can see a list of all available help topics. Powershell documentation reminded me of the manpages in unix computer and the RTM mantra.

Strings, variables, objects:

Declaring and working with variables is very simple. It can be achieved via cmdlets such as "New-Variable", "Set-Variable". Also, we can declare it like one would do it in scripting languages like perl, php.

PS SQLSERVER:\> $rnd = New-Object "Random"
PS SQLSERVER:\> $rnd.Next()
778277127
PS SQLSERVER:\> $str = "Me"
PS SQLSERVER:\> $i = 1


In the output above, we declared a variable namely <var>$rnd</var> using the Random class in .NET framework. The next line invoked the Next() method to generate the random number. The New-Object cmdlet can help us instantiate any .NET framework classes. However, keep it in mind that we have access to a subset of .NET framework classes. We can refer to any class that SMO can refer to. That's the only constraint I found here. In addition to building reference type variables, we can also create primitive types such as string and integer. The example above $str, $i does that respectively.

How do I know which variable is of which type? It's fair question due to the fact that there are no enforcement of type declaration. We simply call the method GetType() on the variable. See the output below.

PS SQLSERVER:\> $i.GetType()

IsPublic IsSerial Name            BaseType
-------- -------- ----            --------
True     True     Int32           System.ValueType


There are special variables in powershell. Here is a list of them and what they do:

1. $_      - Contains the current object in the pipeline, used in script blocks, filters, and the where statement.
2. $Args   - Contains an array of the parameters passed to a function from command line.
3. $Error  - the object containing error information.
4. $Home   - user's home directory.
5. $PsHome - Windows PowerShell installation directory.


Points of Interest

I presented the article materials at the SQL Server user group several months ago. I learned from one of the MS employee that powershell 2.0 was coming out. The new version is expected to cover remoting issues.

History

None Yet

License

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


Written By
Architect
United States United States
Over the course of his 16+year career, Rajib Bahar has been a creative problem solver, finding innovative solutions to clients’ data questions, issues and challenges. He works primarily in Business Intelligence, and Data analytics practice with experience in BigData, DataScience, & Cloud computing environments. His career initially started in the unix world submitting perl and fortran jobs to super-computers back in 2000. This was before Big Data and distributed computing got Big. Later on, he moved on to .NET application development roles, and worked with variety of Database systems such as MS Sql Server, MySQL, PostgresSQL, DB2, & Oracle. Around 2008, he started working in Business Intelligence and/or Datawarehousing practice utilizing both Ralph Kimball and Inmon methodologies. Currently, he is working in Big Data platforms and connecting it with SQL Server 2016, R, Python, and building POCs on Data Science for BI projects. He also enjoys working with visualization tools such as Power BI, Tablue, and QlikView. His recent venture in the Data world includes a podcast on BigData, Data Science, DBMS, analytics, and cloud computing. The podcast is also syndicated across iTunes and YouTube. The link to podcast is http://www.soundcloud.com/data-podcast.

He has also served as a Board of Members of directors at KFAI radio, PASSMN, and various other non-profits. His expertise in data have led to savings at KFAI radio on expensive software license costs, reduced paper expense via online voting. Currently, he spends time contributing to the Data Visualization challenge the station faces.

Feel free to connect with Rajib @rajib2k5 or linkedin.com/in/rajibb

Comments and Discussions

 
GeneralGreat beginner example Pin
b-itguy14-Jul-11 8:20
b-itguy14-Jul-11 8:20 
GeneralMy vote of 1 Pin
Mike Sargent15-Dec-08 5:28
Mike Sargent15-Dec-08 5:28 
QuestionRe: My vote of 1 Pin
Rajib Bahar15-Dec-08 8:35
Rajib Bahar15-Dec-08 8:35 
I'll consider giving your message a rating of 5, if you can suggest few ways to improve it, and what your expectation was for a beginner level. Just FYI, This is only part 1 of a series of articles.


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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.