PowerShell with a Purpose Blog

Calling PowerShell from a .NET Application

Quick example: Here's some C# syntax that, used within a .NET application, will instantiate PowerShell, run this command:

Dir | Where-Object -filterscript { $_.Name -like "d*" }

And return the results as a collection of objects. You'll need to have your project reference the PowerShell Reference Assemblies, which are included in the free Windows SDK installer.

Collection results = PowerShell.Create()
     .AddParameter("filterscript", ScriptBlock.Create('$_.name -like "d*"'))

An even shorter form of syntax lets you just jam a complete command into PowerShell and get back results. This one runs Dir:

Collection results = PowerShell.Create().AddScript("dir").Invoke()

Thanks to fellow MVP Oisin Grehan for his help with that. The upshot of all this is that any .NET application - yes, even ASP.NET - can leverage PowerShell commands. With SharePoint, Exchange, much of System Center, and other products becoming PowerShell'ed, this is a huge timesaver for devs.
Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.