Skip navigation

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()
     .AddCommand("dir")
     .AddCommand("where-object")
     .AddParameter("filterscript", ScriptBlock.Create('$_.name -like "d*"'))
     .Invoke()

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

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.
Publish