Calling PowerShell from a .NET Application

Here's a quick tip for calling PowerShell from a .NET application.

Don Jones

January 12, 2011

1 Min Read
the word powershell on a green wall of code
Alamy

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.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like