Getting Started with Powershell Scripts

Page 2


Next, we'll try calling a webservice from a Powershell script. The tricky part about this solution, is first you need to create a compiled DLL (Dynamic Linked Library) from your web service's WSDL (Web Service Definition Language). An easy way to do this, is by using wsdl.exe from Visual Studio's command prompt. Once you have your web service proxy class compiled into a DLL, you can call it like this:

$parameter1 = $args[0]
$parameter2 = $args[1]

[Reflection.Assembly]::LoadFrom("$pwd\yourWebService.dll")
$objService = new-object yourWebService
$output = $objService.yourServiceCall($parameter1,$parameter2)
write-output $output

First, $parameter1 and $parameter2 are assigned to the first two arguments given when running the script. The DLL is loaded using Reflection and is instantiated ($objService). Once that is done, the exposed service "yourServiceCall" is called from the $objService object, with $parameter1 and $parameter2 as arguments. Finally, the resulting data is written to the STDOUT (Standard Output). Of course, the big problem with this type of solution is that you'll have to recompile your proxy class each time the service changes.


For this next example, we'll look at Powershell's for-each construct. This script is named "checkConfig.ps1", and it is used to verify the presence of certain lines of text in a config file. It can be very useful to verify a .Net web.config file (for a large ecommerce website), which can get quite large. Here's the code:

$FileName = $args[0]
$List = get-content schStrings.txt

foreach ($Env in $List)
{
get-content $FileName -encoding utf8 | select-string $Env
}

First, this script retrieves the name of the file to be verified (from the script's first argument given on the command line), and stores it in the $FileName variable. Next, it initializes the $List variable with the contents of the schStrings.txt file. The "foreach" iterates through each individual search $Env string in $List, attempting to find only those lines in the file (by piping it to the select-string cmd-let). The matches are then sent to the STDOUT, as there is no variable assigned to hold the values returned by the get-content cmd-let.


Powershell's ability to expose the .Net framework to command-line-based scripts makes it a very powerful tool in its own right. What we've done here only scratches the surface, but it should be enough to get you started. Happy Powershelling!


Aaron Ploetz

Page: <Previous Page> 1 2


References:

Hanselman, S. (2006), Signing PowerShell Scripts, http://www.hanselman.com/blog/SigningPowerShellScripts.aspx


Microsoft TechNet (2009), About Execution Policies, http://technet.microsoft.com/en-us/library/dd347641.aspx

Copyright © Aaron Ploetz 2010 -
All corporate trademarks are property of their respective owners, and are shown here for reference only.