using System; using System.Management.Automation; using System.Management.Automation.Runspaces; namespace PowershellExample { /// /// This program demonstrates the shared use of a class between C# code and a Powershell runspace /// Ce programme démontre l'utilisation d'une classe entre du code C# et un runspace Powershell /// public class Program { static void Main(string[] args) { // First example, we create the class from C# // Premièr exemple, on créé la classe depuis le C# InstantiatedClass ic = new InstantiatedClass(0); Console.WriteLine(ic); // Don't forget, Runspace implements IDisposable // N'oubliez pas que Runspace implémente IDisposable using (Runspace rs = RunspaceFactory.CreateRunspace()) { rs.Open(); // We share our instance using the Runspace's SessionStateProxy // On partage notre instance via une variable du Runspace via la propriété SessionStateProxy rs.SessionStateProxy.SetVariable("myVariable", ic); // We loop until SomeNumber reaches 10. Each iteration will increment SomeNumber by 2: +1 from Powershell and +1 from C# // On boucle jusqu'à ce que SomeNumber atteigne 10. Chaque itération incrémentera SomeNumber de 2: +1 depuis Powershell puis +1 depuis le C# while (ic.SomeNumber < 10) { using (Pipeline pipeline = rs.CreatePipeline("$myVariable.SomeNumber = $myVariable.SomeNumber + 1")) pipeline.Invoke(); Console.WriteLine("powershell: " + ic); ic.SomeNumber++; Console.WriteLine("C# : " + ic); } } Console.WriteLine("Done first example/Fin du premier exemple"); Console.WriteLine(); // In our second example, we instantiate the object from Powershell // Dans notre second exemple, on instantie l'objet depuis Powershell using (Runspace rs = RunspaceFactory.CreateRunspace()) { rs.Open(); // We instantiate our object with the new-object commandlet // On instantie un nouvel objet via new-object using (Pipeline pipeline = rs.CreatePipeline("$mySecondVariable = new-object PowershellExample.InstantiatedClass(100)")) pipeline.Invoke(); ic = (rs.SessionStateProxy.GetVariable("mySecondVariable") as PSObject).BaseObject as InstantiatedClass; while (ic.SomeNumber < 110) { // Method call // Appel de méthode using (Pipeline pipeline2 = rs.CreatePipeline("$mySecondVariable.IncrementSomeNumber()")) pipeline2.Invoke(); Console.WriteLine("powershell: " + ic); ic.SomeNumber++; Console.WriteLine("C# : " + ic); } } Console.WriteLine("Done second example/Fin du deuxième exemple"); Console.ReadLine(); } } public class InstantiatedClass { public int SomeNumber { get; set; } public InstantiatedClass(int someNumber) { this.SomeNumber = someNumber; } public void IncrementSomeNumber() { this.SomeNumber++; } public override string ToString() { return string.Format("ic={0}", this.SomeNumber); } } }