November 14, 2009

Invoking WCF from PowerShell

To invoke WCF from PS

1. Environment setup for PS

2. Create & bind proxy

3. Use API to invoke WCF

Following script demonstrates how to access Calculator service using PS.

Windows PowerShell
Copyright (C) 2006 Microsoft Corporation. All rights reserved.

PS C:\Documents and Settings\amungale\Desktop\WCF\HelloService\bin\Debug> cd "C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin"
PS C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin> .\vs80vars.ps1
PS C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin> .\svcutil.exe http://localhost:8000/ServiceModelSamples/service?ws
dl
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.2152]
Copyright (c) Microsoft Corporation. All rights reserved.

Attempting to download metadata from 'http://localhost:8000/ServiceModelSamples/service?wsdl' using WS-Metadata Exchange
or DISCO.
Generating files...
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\CalculatorService.cs
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\output.config
PS C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin> csc /t:library CalculatorService.cs /r:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\System.ServiceModel.dll"
Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.3053
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.

PS C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin> [Reflection.Assembly]::LoadWithPartialName("System.ServiceModel")

GAC Version Location
--- ------- --------
True v2.0.50727 C:\WINDOWS\assembly\GAC_MSIL\System.ServiceModel\3.0.0.0__b77a5c561934e089\System.ServiceModel...


PS C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin> [Reflection.Assembly]::LoadFrom("$pwd\CalculatorService.dll")

GAC Version Location
--- ------- --------
False v2.0.50727 C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\CalculatorService.dll


PS C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin> $wsHttpBinding = new-object System.ServiceModel.WSHttpBinding
PS C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin> $endpoint = new-object System.ServiceModel.EndpointAddress("http:/
/localhost:8000/ServiceModelSamples/service"
)
PS C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin> $calcService = new-object CalculatorClient($wsHttpBinding, $endpoi
nt)
PS C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin> $calcService.Add(3,4)
7

Additional References:

http://keithhill.spaces.live.com/blog/cns!5A8D2641E0963A97!512.entry
http://keithhill.spaces.live.com/blog/cns!5A8D2641E0963A97!645.entry