Monday, January 28, 2013

Passing .Net objects as arguements to PowerShell

In the previous posts about PowerShell to .Net integration, the samples were simply invoking PowerShell scripts from .Net code. In the first post, the sample don't have any parameter at all. It just executed a get-alias command from .Net code. The second which I wrote in relation with DSL, passes the arguments as parameters to a dynamic block which uses '&' for script block execution. The below code snippet is just for  a reference regarding dynamic script block execution.


         private  static  void  RunPowerShellScriptDynamicallyWithParameter(int  inputNumber)
         {
             PowerShell  ps = PowerShell .Create();
             //The format needed for PS to execute dynamic scipr block is 
             //&{param ($paramsAsCommaSeparated);statements;} inputParameters as string 
             string  script = "&{param ($number);if (($number % 2)-eq 0)'}} " +inputNumber.ToString();
             ps.AddScript(script);
             ps.AddParameter("number" , inputNumber);
             Collection <PSObject > result = ps.Invoke();
             //Process logic for resultant PSObjects. 
         }
 


C#/VB.Net objects to PowerShell

There was a small limitation that we can append only string variables / primary datatypes as it uses string concatenation for passing the arguments.To achieve actual object parameter passing in a simple manner you need to define the parameters at the beginning of the script block you want to execute. Then from the .Net code add those parameters.Here is a small code block which validates an .Net FixedDeposit object in powershell code.

         FixedDeposit  fdAccount = new  FixedDeposit () { Customer = new  Customer  { Name = "George" , Age = 70 }, Interest = 9.0 };
         private  void  RunPowerShellScriptWithParameter()
         {
             PowerShell  ps = PowerShell .Create();
             string  script = "param($fd); if ($fd.Customer.Age -ge 60) {$fd.Interest=$fd.Interest+.5}" ;
             ps.AddScript(script);
             ps.AddParameter("fd" , fdAccount);
             Collection <PSObject > result = ps.Invoke();
             //Inspect the fdAccount object for changes 
         }
 

In India all the banks give additional .5 interest to senior citisons (above 60) for their fixed deposits. If this rule comes via a script it can be modified at any time.PowerShell scripts can be also applied to the UI elements ie we can modify / control the .Net UI elements from PowerShell

No comments: