Search code examples
c#visual-studio-2010powershellasmxwebmethod

Web Method and PowerShell


I see a lot of information on running a Web Method from PowerShell, but is it possible to run a PowerShell command as part of a Web Method. For instance maybe run a simple ls command and have it return the output?


Solution

  • You can easily host the PowerShell engine in C# code:

    using System;
    using System.Management.Automations;
    
    ...
    using (var ps = PowerShell.Create()) {
        ps.AddScript(@"Get-ChildItem c:\");
        var results = ps.Invoke();
        foreach (dynamic result in results) {
            ...
        }
    }