How to run PowerShell script from command-let

Sometimes, we want to run PowerShell script from command-let that derives from PSCmdlet (If you derived from Cmdlet, you can't use this way).
To do so, we just have to use this code:

   1:  using System.Management.Automation;
   2:  using System.Collections.ObjectModel;
   3:   
   4:  ......
   5:   
   6:  Collection<PSObject> results = InvokeCommand.InvokeScript("dir" /*replace it with your script */);
   7:  foreach (PSObject var in results)
   8:  {
   9:         WriteObject(var.ToString(),false);
  10:  }

I included in this code the important using statements, and the code itself. Few things about this code:

  1. I use PSObject as the type for the collection, which means that I can access any property and method of the returning object, include Extended methods (ETS).
  2. Always use WriteObject method in Command-lets NEVER use System.Console.
    That's because WriteObject write stream of object, not text, which is one of the biggest advantages in PowerShell - we can work with object instead text.
    When you use WriteObject you can be sure that any PowerShell host will be able to use the command-let and the output easily.

Shahar.

2 Comments

Comments have been disabled for this content.