Discovering Windows PowerShell

March 27th, 2008

I am currently working in a new development environment, unlike any that I have used in the past. It is different for two reasons, magnitude of dependencies and build process. The warning I have been given is, "this is a complex beast with lots of stuff in it, and much can go wrong." That statement pretty much covers the magnitude of dependencies stuff. As for the build process, my first question asked was, "you mean we don’t use ‘Ctrl+Shift+B’ (in Visual Studio)?" No, we build using a command-line style approach, outside of the IDE.

Due the dependencies and build process, I wanted to schedule nightly builds on my local machines. This was when I discovered Windows PowerShell. PowerShell uses the .NET CLR and the .NET framework to provide new tools and methods for administering Windows environments. While similar in some aspects as DOS, PowerShell is much more. It is a command-line shell and scripting language that allows administrators to use C#.

Each night I want to backup certain files, sync files, clean and build my projects for 32 and 64 bit systems, update my environment with dependency changes, and email myself the log files generated during this process. I am not a DOS command nor scripting guru, but I could figure this out with some time. With PowerShell, I can leverage my C# knowledge to do all these tasks in a short amount of time.

If you want more control over administering your environments and would like to use C#, check out PowerShell. There is a good amount of support and tutorials to help get started.

Trivial Examples

The following is a trivial example of how to connect to a SQL database, query the Employees table of the Northwind database, and write those results to the screen. The PowerShell scripting syntax can be seen below.

   1: $conn = New-Object System.Data.SqlClient.SqlConnection
   2: $conn.ConnectionString = "Data Source=.;Database=Northwind;"
   3: $cmdText = "SELECT TOP 10 * FROM EMPLOYEES"
   4:  
   5: $conn.Open()
   6: $cmd = New-Object System.Data.SqlClient.SqlCommand($cmdText,$conn)
   7: $rdr = $cmd.ExecuteReader()
   8:  
   9: while($rdr.Read())
  10: {
  11:     $id = $rdr["EmployeeID"].ToString()
  12:     $fn = $rdr["FirstName"].ToString()
  13:     $ln = $rdr["LastName"].ToString()
  14:     Write-Host "$id $fn $ln"
  15: }
  16:  
  17: $conn.Close()

While that example is extremely trivial, it does show the power of using C# logic with the PowerShell language. It is easy to see how the code example above was translated from C# into PowerShell. The differences are syntactic.

For my nightly build scenario, I am able to create a scheduled task that calls a batch file, with similar contents as below.

   1: REM Calling Nightly Build
   2:  
   3: REM do the necessary to clean and build my environment
   4: call MyBuildLogicFile.bat
   5:  
   6: REM call powershell scripts
   7: powershell -command "& C:\PowerShellScripts\MyBuildScript.ps1

The batch file does the building then calls a PowerShell script I created to do help me parse my log files and email the contents. It actually call two scripts, one for parsing the content of my resulting log file, and the other to email the contents of the log file. The contents of the two files can be seen below.

PowerShell provides a number of predefined methods that can be used out of the box. Since I am interested in reading a log file, parsing its contents, and emailing the results, there are some functions available for making this scenario easier. For example, I do not need to recreate the wheel to read in a file’s contents. I can use Get-Content. Before getting carried away with writing too much C#, check the available cmdlets (commandlets) to see if your desired functionality exists.

My file content parser script, using Get-Content.

   1: # Create a StringBuilder to retain our log file contents
   2: $sb = new-object System.Text.StringBuilder
   3:  
   4: # append a line break point, <br/> for the log file contents
   5: foreach ($line in get-content "C:\Output.log")
   6: {
   7:   $sb.Append($line).Append("<br/>")
   8: }
   9:  
  10: # Call our Emailer.ps1 to send this content to us
  11: powershell -command "& C:\PowerShellScripts\Emailer.ps1 -param '$sb'"

My email script that is called from the above code.

   1: param($param1) 
   2:  
   3: $message = new-object System.Net.Mail.MailMessage("me@mail.com", "me@mail.com")
   4: $message.IsBodyHtml = $True
   5: $message.Subject = "Automated Build Update"
   6: $message.Body += $param1;
   7:  
   8: $smtp = new-object Net.Mail.SmtpClient(”smtp.mail.com”, 587) 
   9: $smtp.EnableSsl = $True
  10: $smtp.Credentials = new-object System.Net.NetworkCredential("username", "password")
  11: $smtp.Send($message)

 

Pretty simple. Thanks to PowerShell, I have more control over administering my development and test environments using my preexisting knowledge of C#. One command that was always useful in Unix/Linux is grep. PowerShell uses Regex to simulate similar functionality, and you can find examples of those online.

Alex Mueller

  • http://elegantcode.com dcarver

    You might also want to check out http://www.powershell.com/ whch is a free powersheel development IDE

  • http://blog.cwa.me.uk/2008/03/28/the-morning-brew-61/ Reflective Perspective – Chris Alcock » The Morning Brew #61

    [...] Discovering Windows PowerShell – Alex Mueller takes a first look at PowerShell with some examples [...]

  • http://forum.fachinformatiker.de/skript-webserverprogrammierung/115683-ps-max-profilgroesse-mail.html#post1047306 [ps] max Profilgr??e / mail – Forum Fachinformatiker.de

    [...] ] du hast dich bem?ht und eine suchmaschine benutzt. Elegant Code Discovering Windows PowerShell den rest findest du vielleicht selbst. s’Amstel __________________ Help stamp out and abolish [...]

blog comments powered by Disqus