May 22, 2008

Programming with PowerShell

Introduction
I'm in a project to program PowerShell to control ActiveDirectory and ExchangeServer2007.
It was my first time to use PowerShell, and I had a lot of trouble to find help about
writing PowerShell scripts. So, for my next time, and for people who's looking for more
information, I would write down what I learned during this project.

About PowerShell
PowerShell is a name of Microsofts' new Shell Environment and its' Script language.
It has the same purpose with DOS, but it is made much more powerful and easy to script.
You can use it as a shell or use it as a language to create scripts to manage Windows,
ActiveDirectory(using ADSI), ExchangeServers(using Exchange Snapin). It is based on
.NET Framework technology, so you can call the whole class library to create more
advanced programs.

There is more detail about PowerShell here.
http://msdn.microsoft.com/en-us/library/ms714674(VS.85).aspx


Getting Started

You can get one for Windows XP here.
http://www.microsoft.com/downloads/details.aspx?FamilyID=30125A46-B97C-4704-AA10-605E809D5933

After downloading and installing, you will be able to use PowerShell like your Command Prompt. The basic commands are same with DOS. You can move around with "cd" command, and see inside your current directory using "dir" or "ls".
There are many other dos commands you can use. These commands are not the real commands in PowerShell. They are defined as aliases to a real PowerShell command, to let you use some commands more easily. Execute "get-alias" to see all the aliases and PowerShell commands related to them. The "real" PowerShell commands are called "Cmdlets", and their name are defined like "'Verb'-'Noun'". "get-alias" that I used above, is one of those Cmdlets too.

You can check the Cmdlet list, by executing "get-command".

You can page the list by piping the command to an alias "more".
> get-command | more

For more command information, use the "get-help" Cmdlet.
> get-help | more
> get-help | more

You can use options for more and full information.
> get-help -detailed | more
> get-help -full | more


I think this would be enough to find and use Cmdlets to control PowerShell.

Creating a PowerShell Script
It is not so difficult to read PowerShell commands from a script file and execute it.

First, create a file with ".ps1" extension. like, "helloworld.ps1".
c:\ps\helloworld.ps1

write-host "helloworld!"


Next, call your script in powershell.
> cd c:\ps
> .\helloworld.ps1

The script will be executed, and you'll see a message output.
> helloworld!

No comments: