This is a mirror of official site: http://jasper-net.blogspot.com/

Calling PowerShell from .NET

| Monday, April 12, 2010
I have been working with Windows Server AppFabric caching lately and have found it to be very impressive.  The more that I work with it the more that I can see areas that it can be utilized.  One of the things that will become quite evident as you start using it is that much of the setup and configuration is done through PowerShell cmdlets.

I am in the process of putting together an application and I want the application to be able to create and pre-populate the cache.  As I looked into creating the cache I knew that it could be created through PowerShell directly but I wanted to call the PowerShell cmdlets from .NET.  So, lets look at what is needed to create the cache from PowerShell first and then we will look at the code to call the cmdlets from .NET.

This assumes that AppFabric has been installed and configured.

Open a PowerShell command window.  The first thing that we are going to do is to import two modules and then we can start issuing commands.  First, type "Import-Module DistributedCacheAdministration" (without the quotes) and hit enter.  This will import the cache administration cmdlets. Next type "Import-Module DistributedCacheConfiguration" and hit enter.  This will import the cache configuration cmdlets.

The next command will bring the current machines' cluster configuration into the PowerShell session context.  So, type in Use-CacheCluster and hit enter.  We have now entered all that we need to start interacting with the cache.  The first thing that we need to do is to ensure that the cache service is running.  Type "Get-CacheHost" and hit enter.  Look on the screen and see if the Service Status show UP.  If it shows DOWN then issue the following commands to start it.  Type "$hostinfo = Get-CacheHost" and hit enter.  Then type in "Start-CacheHost $hostinfo.HostName $hostinfo.PortNo".

At this point we are ready to create the cache using the New-Cache cmdlet.  Type "New-Cache <your cache name here>" and hit enter.  This will create a cache with your name that is ready to use.

If you want to see the configuration for your newly created cache type in "Get-CacheConfig <your cache name here>" and hit enter.  You will see the following configuration attributes and their settings.

CacheName : MyCache
TimeToLive : 10 mins
CacheType : Partitioned
Secondaries : 0
IsExpirable : False
EvictionType : LRU
NotificationsEnabled : False


To do this all with code we need to add three references to our project.  Add the System.Management.Automation assembly as well as the Microsoft.ApplicationServer.Caching.Core and Microsoft.ApplicationServer.Caching.Client assemblies.  These two assemblies can be found in the Windows\System32\AppFabric directory.

Read more: Stephen Kaufman's WebLog

Posted via email from jasper22's posterous

0 comments: