grokgarble.com

Database, Software, and System Engineering

Execute PowerShell from a ASP.NET Web Application

I had an interesting request come in to automate existing server-side PowerShell processes that have been initiated by server admins thus far locally on the server, using a web interface instead.  Turns out, the admins want to offload the work back to the business users so it can be more on demand. Essentially, they want the non-techies to reuse what the techies have been using server side without having to involve 1) the techies, 2) the overhead of logging in to the server, or worse 3) the business users perform PowerShell commands server side (..and therefore running the risk of executing something incorrectly and/or making a security admin’s head explode).

No problem.  Here’s a quick demo on how it can be done.

Our plan of attack will be to build a web form project using Visual Studio 2012 and .NET Framework 4.5.  It will execute server side and scripts of PowerShell commands using the framework’s PowerShell class from the System.Management.Automation name space.  The response I’ll handle as a string, and paint it to a Text box

Here we go…

First, create the Empty Web Application called PowerShellExecution.

PowerShell-BlankWebApplication

Next, add a New Item… of Default web form named “Default.aspx” to the solution to align with the demo content below.

Now, copy and paste over the default Default.aspx code that’s generated with the below for the quick UI test:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PowerShellExecution.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
    <div>
        <table>
            <tr><td>&nbsp;</td><td><h1 align="left">PowerShell Command Harness</h1></td></tr>
            <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
            <tr><td>&nbsp;</td><td>PowerShell Command</td></tr>
            <tr><td>
                <br />
                </td><td>
                <asp:TextBox ID="Input" runat="server" TextMode="MultiLine" Width="433px" Height="73px" ></asp:TextBox>
            </td></tr>
            <tr><td>
                &nbsp;</td><td>
                <asp:Button ID="ExecuteCode" runat="server" Text="Execute" Width="200" onclick="ExecuteCode_Click" />
            </td></tr>
                <tr><td>&nbsp;</td><td><h3>Result</h3></td></tr>
                <tr><td>
                    &nbsp;</td><td>
                    <asp:TextBox ID="ResultBox" TextMode="MultiLine" Width="700" Height="200" runat="server"></asp:TextBox>
                </td></tr>
        </table>
    </div>
</form>
</body>
</html>

Next, to get the System.Management.Automation name space included in our solution we need to install the System.Mangement.Automation package.  To do that, under the Tools menu select Library Package Manager >> Package Manager Console

PowerShell-VisualStudioLibraryPackage

…within the Package Manager Console execute “Install-Package System.Management.Automation”

PowerShell-NuGet

After a successful execution of that package install, you’ll want to add the reference to your Default.aspx.cs file:

using System.Management.Automation;

I’m going to use a button’s onclick action to invoke the method that will perform the magic of submitting and reading the response from my PowerShell.  The remaining item to address, that may vary on your circumstance, is how to handle the response from the PowerShell.

Remember, everything in PowerShell is returned as an object.  We need to display our object back on the page as a string for this demo.  You’ll need to be mindful of that when executing, as well as how or what you’re wanting your results displayed on the page.

To ensure that happens for me, I am going manage the output of my PowerShell execution by building a string out of the objects returned.  I’ll paint those string casted results in a TextBox control called “ResultBox” using the StringBuilder class within in the System.Text name space.  Therefore, I need to reference that name space as well in my code behind.

using System.Text;

Below is my complete Default.aspx.cs code for the purposes of this demo.  It includes the above references  I discussed, the default page load, and especially the onclick method to support the execution details submitted to the Input control using the PowerShell class.

I sprinkled in comments for context:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Text;

namespace PowerShellExecution
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ExecuteCode_Click(object sender, EventArgs e)
        {
            // Clean the Result TextBox
            ResultBox.Text = string.Empty;

            // Initialize PowerShell engine
            var shell = PowerShell.Create();

            // Add the script to the PowerShell object
            shell.Commands.AddScript(Input.Text);

            // Execute the script
            var results = shell.Invoke();

            // display results, with BaseObject converted to string
            // Note : use |out-string for console-like output
            if (results.Count > 0)
            {
                // We use a string builder ton create our result text
                var builder = new StringBuilder();

                foreach (var psObject in results)
                {
                    // Convert the Base Object to a string and append it to the string builder.
                    // Add \r\n for line breaks
                    builder.Append(psObject.BaseObject.ToString() + "\r\n");
                }

                // Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
                ResultBox.Text = Server.HtmlEncode(builder.ToString());
            }
        }
    }
}

Copy and paste that in and you’re ready to test…

Once rendered in your browser, type into the “PowerShell Command” window Get-Service | Out-String (or your favorite cmdlet for a test).

UITest

Remember, port everything to the Out-String cmdlet so it can be handled properly by the StringBuilder class.  Otherwise, you’ll get stringbuilder output of the data type details of the objects returned by your cmdlet – one long get-member call, most likely not what you’re after.

If you’re wondering if you can run scripts that are on the local file system of the server, the answer is yes.  Simply pass the script location an parameters in string form to the AddScript() method within Default.aspx.cs using double slashes format.

//shell.Commands.AddScript(Input.Text);
shell.Commands.AddScript("C:\\Scripts\\PowerShell\\PowerShellScript.ps1");

Contents of this test PowerShellScript.ps1 (same as what was used in the Input control):

Get-Service | Out-String

(I removed the Input box control and test again the solution below)

UITest

Note: To run this on a server, the ApplicationPool hosting your application will have to have administrator rights.

There you have it, a quick server side PowerShell web method.

 

92 thoughts on “Execute PowerShell from a ASP.NET Web Application

  • asotelo@dfckc.com' Antonio says:

    Thank you for this solution. However I am unable to get the output of the powershell script displayed in the Results text box. No errors either. Any ideas?

    • Jeff Murr says:

      Antonio, what us the count of results? Can you display or the builder text using System.Diagnostics.Debug.Writeline()? I’d start there.

    • apanse10@gmail.com' Ameya says:

      Antonio,

      Were you able to fix this? I’m getting the output when I type the comands in the input box but when I try to run the .ps1 script, output is empty.

  • spoomani@ntrustinfotech.com' Poomani S says:

    I am getting error message like below

    “An error occurred while attempting to load the system Windows PowerShell snap-ins. Please contact Microsoft Customer Support Services.”

    • Jeff Murr says:

      Are you sure PowerShell is installed correctly? If you execute “powershell” from cmd will it start?

      This command should be a GAC location if you get PowerShell started:

      write-host ([PSObject].Assembly.Location)

      Does System.Management.Automation.dll exist on your machine?

      Without seeing my systems responses from that level of troubleshooting remove/readding or updating PowerShell may correct these kinds of errors are my initial thoughts.

      Let me know what you find.

      • kopparthiraviteja@gmail.com' raviteja says:

        Hi Jeff Murr, I Worked above code its working with powershell commands only but not with powershell scripts i.e shell.Commands.AddScript(“C:\\temp\\dotnet.ps1″);.so please solve this that I want to execute poweshell script in .net.please give code that if any modications will be ther e,thank you verymuch

  • eacuervo@gmail.com' Eduardo Cuervo says:

    This is very cool. thanks for the great article.

    I have a question. Does this work with any command? As in commands from an imported module? For some commands I get no response, but I can tell that they were not executed.
    Is there a way to get an error message when things dont work. It seems to fail silently.

    Thanks for writing this.

    • Jeff Murr says:

      Hi Eduardo,

      Thanks! Debugging and error trapping would be my suggestion. Depending one the return type, you may need to add in some references and handle them correctly. I’m only dealing in strings. If you have a specific example that might help narrow down a solution for you.

      Jeff

      • tenaciousgeo@gmail.com' Geo says:

        Hi Jeff, with regard to debugging and error trapping, I would love to see an example how to do that. For example, with the current code if you do a Test-Connection cmdlet to a computer that is offline, there is no result on the webpage instead of showing the ‘ResourceUnavailable’ error returned. What would be the way to look for and handle errors this way to display a result?

        • Jeff Murr says:

          Geo,

          Sorry for the late reply, good question though. I’d first wrap the “var results = shell.Invoke();” in a try/catch and specifically target the ResourceUnavailable exception there; otherwise, inspect the return as a string and handle it specifically with some kind of workflow. Other options are handle the exception in the script and pass back some kind of string text for inspection in your code behind.

          Jeff

      • kopparthiraviteja@gmail.com' raviteja says:

        Hi Jeff Murr,thanks for helping in executing of powershell script in .net but it was working with powershell commands only not with powershell scripts i.e shell.Commands.AddScript(“C:\\temp\\dotnet.ps1″);
        with this i got an error in result box i.e System.ServiceProcess.ServiceController
        so please help me tht i want to execute large script of powershell in .net

      • kopparthiraviteja25@gmail.com' raviteja44 says:

        Hi Jeff Murr,thanks for helping in executing of powershell script in .net but it was working with powershell commands only not with powershell scripts i.e shell.Commands.AddScript(“C:\\temp\\dotnet.ps1″);
        with this i got an error in result box i.e System.ServiceProcess.ServiceController
        so please help me tht i want to execute large script of powershell in .net

  • soroush_jafari@hotmail.com' Soroush says:

    hi Jeff,
    thanks for your guide,
    im new to asp and not familiar with it that much, i run the code successfully i want to extend the usability, i want to show the result in an array or in a dropdown box, and then can select on of the option and run another command but the new user selection

    what i mean is the result can have 5 lines
    i want to show each line as one option of drop down box or i want to store each line separately
    what should i do for that?

  • Thank you for your tutorial, it is really helpfull !

  • Hi Jeff Murr,

    How to execute Hyper-V WMI Provider like Get List of Virtual Machine using ASP.net ?

    Thanks
    Alok

    • Jeff Murr says:

      Alok,

      This can all be done in your script – or you can create different commands based on different end user input with various web forms. The returns would all be string unless you wanted to do more high powered object manipulation. You could go as far as create a very detailed tree of the details provided back from the Hyper-V modules. Endless possibilities.

      Jeff

  • timo.meier86@gmail.com' Timo Meier says:

    Everything works fine, as long as the path of the powershell script has no spaces in it.

    shell.Commands.AddScript(“C:\\Scripts\\PowerShell\\PowerShellScript.ps1″); <= works!

    shell.Commands.AddScript("C:\\Scripts\\Power Shell\\PowerShellScript.ps1"); <= Does not work (result.Count is 0)

    Can you help?

    • Jeff Murr says:

      Timo, sorry for the late response. I’d format the string of the path in @ notation.

      Example:

      string value = @”C:\directory path with spaces\script.ps1″;

      Otherwise, remember you can always work with the System.IO.Path objects and get them out to strings.

  • samuraichamploo59@gmail.com' adminsys says:

    Hi, thanks for your tutorial.
    But I have an error when i open the default.aspx : Error cannot load the type ‘PowerShellExecution.Default’.

    Have you an idea ?

    • Jeff Murr says:

      Possibly the dll is not registered. Either that, or a dependency is not registered? Sounds like a PowerShell installation issue. Can you run powershell at all on the machine? Next, I’d point to architecture issues. 32bit vs. 64bit installation issues either for your app or PowerShell.

  • markos@envox.hr' Kenneth Parker says:

    I cannot get local script to work! When I use

    shell.Commands.AddScript(“C:\\Scripts\\PowerShell\\PowerShellScript.ps1″);

    I get no results. The path is correct, the command in script is trivial, Get-Service | Out-String. What am I missing?

    • Jeff Murr says:

      Make sure you’re using an elevated user and script execution policy isn’t breaking you. Perform some more try/catch usage to find what is silently failing. Other than that I’m not sure. Good luck!

  • mar10c@cox.net' MC says:

    Jeff,
    This works:
    shell.Commands.AddScript(Input.Text);

    This one Does Not work:
    shell.Commands.AddScript(“C:\\Scripts\\PowerShell\\PowerShellScript.ps1″);
    I stepped into the code and the results.Count = 0

    Any suggestion?

    • Jeff Murr says:

      Check the execution policy of your local machine. Get-Executionpolicy, see if that leads you to the problem. Otherwise, kick off some try/catch error handling to highlight where a silent exception might occur. If all else fails, start in debug mode and walk through everything.

  • 127021@myrp.edu.sg' New to C# says:

    Can I get a copy of the file?

    And also, I can’t find the ResultBox. (I’m using MVC 4 web application)

    And if I wish to do the powershell remotely from current server to another server, would it be possible?

    • Jeff Murr says:

      I don’t have the original source code anymore; but I should link my blog to a repo for future posts. This is a hobby, but one I want folks to get some use out of and my completed source I should make more standard and readily available.

      ResultBox is a forms control. The world changes in MVC, for that you’ll need to add a controller to handle the text output. For that approach I’d point you back to MSDN. I’d have to overhaul a lot in the post to answer the question accurately and wouldn’t want to derail in comments.

      The .NET namespaces shouldn’t change on the approach of executing the PowerShell, you’ll just need to modify how to handle the response a custom controller.

    • bbsing@comcast.net' bbsing says:

      The reason users can’t find the ResultBox is because they probably the primary namespacein the Default.aspx.cs isn’t PowerShellExecution or the the Default.aspx.designer.cs file doens’t have the poroper namepace declaration … ie PowerShellExecution

      change those to match and you should be good to go.

  • patrickdierken_bw@arcor.de' SPN says:

    Thank you for this well-written article. I’m quite new to C# and ASP.NET, so it’s good that you described all steps, even if they might seem obvious to pros (i guess).

  • darrel.towndrow@gmail.com' DT says:

    Thanks for the guide Jeff, I found it very useful and easy to follow.

  • modiami90@yahoo.co.in' Ami says:

    This is a too good article but can please help me to use Renci.SshNet library so that everything happens securely. I am deadly needing this.

  • cdejuansmith@gmail.com' CD Smith says:

    Mr. Murr,
    This was a fantastic article…I have one question, if wanted this same example to execute Exchange Powershell commands?

    I used your example on an Exchange server but it only ran the base Powershell commands. Would the code need to contain some authentication to the Exchange server? Would the code need to execute the Exchange Powershell snap in?

  • clancg@hotmail.com' surge3333 says:

    Similiar to some others, I can get the input box to work, but not a local script.

    This doesn’t produce any results. No errors. Nothing.

    shell.Commands.AddScript(“C:\\Scripts\\PowerShell\\PowerShellScript.ps1″);

    The command is a simple Get-Service | Out-String.

    It works fine when executed from a Powershell prompt.

    Was anybody ever able to resolve this issue?

    Thanks

  • andreas@powerdeploy.com' Andreas says:

    Awesome post!

    This was really helpful :)

  • chomp66@hotmail.com' Lucas says:

    For all of you who have had problems with the issue of not being able to execute the script the issue is likely the execution policy … on BOTH the x86 and x64 versions of powershell that are likely installed on your machine. If you go to Start –> All Programs –> Accessories –> Windows Powershell you probably see x2 versions of powershell and x2 versions of powershell ISE.

    You have 2 options. 1 – Delete the x86 version because you don’t need it or 2 – launch them both as admin and set-executionpolicy to either unrestricted or remotesigned.

    That should fix the script issue.

  • alex@pikori.com' Neuro says:

    Thank you so much Jeff this was really usefull.

    One quick thing though I am trying to pass in some parameters to a script, and for some reason it just wont work. I have tried to add them to the end of the AddScript line, and I have also tried to use the AddParameter funtion, still with no luck. I was hoping you would be able to shed some light on what I am doing wrong :)

    Cheers,
    Neuro

    • Jeff Murr says:

      Tried AddCommand() and AddArgument()?

      PowerShell psExec = PowerShell.Create();
      psExec.AddCommand(@”C:\Test-Date.ps1″);
      psExec.AddArgument(DateTime.Now);

  • shrikkanth.k@gmail.com' Shrikkanth says:

    Hi Jeff,

    This is a great article. I took inspiration from this article and created a website which basically shows all the VM in my subscription in a Grid and the inline start and stop VM option. Everything worked as expected.
    I tried to host the application in IIs on my local and the page doesnt load at all. Not sure what is the issue. I am using Windows 7 with IIS7.5.

  • hi instead of outputting all results to the result box, how would I output the contents of a variable on the asp site?

    for example, if I had a variable in my powershell script called $test = 1; how could I display the contents of $test on the site?

    cheers

    • Jeff Murr says:

      The important thing to remember is that everything in PowerShell is an object. The results need to be type casted and then converted to string (if the aren’t already). The ResultBox.Text is C# for the code behind assigning the results of the string builder that is the output of the command. The same should be capable for any C# variable you’d like to use and then assign that value to you web form.

  • mohdazam89@gmail.com' Azam says:

    Can you please shed more light on the below error:
    Parser Error Message: Could not load type ‘PowerShellExecution.Default’.

    what dll its refereing to ….

    The Article is awesome.
    Thanks Jeff

    • Jeff Murr says:

      Do you get this when you’re interacting with PowerShell on its own? Keep in mind the issues with 32bit vs. 64 bit.

    • arunkarthik.ev@gmail.com' Arun says:

      In the Default.aspx page, I found changing the first line from

      CodeBehind=”Default.aspx.cs”

      to

      CodeFile=”Default.aspx.cs”

      worked for me :-)

  • sadavala.sree@gmail.com' Sreehari says:

    Thank you so much Jeff this was really usefull.

    is it possible to add computer name input on webpage and redirect to ps1 file?

    if you add remote execution that would be great.

  • johnb@wash.systems' John says:

    I also ran into the error msg: Could not load type ‘PowerShellExecution.Default’. I am running Visual Studio Express 2013 for Web on a 64bit WIN7PRO system. Normally no issues when interacting with PowerShell on it’s own.

    • Jeff Murr says:

      Most likely has a version mismatch with powershell 32 bit. Visual studio is 32 bit. Open the powershell 32 bit version and make sure you’ve allowed unrestricted execution.

  • […] For what you want (linking a user control in a web page to the execution of a specific action on the server), you might want to look into executing PowerShell from ASP.NET as outlined in this article. […]

  • Partyholes@gmail.com' Dude says:

    Oh wow. Doing badly aren’t I. Here’s another attempt without some HTML stuff….

    Line 1: @ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”PowerShellExecution.Default”
    Line 2:
    Line 3: DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”

  • gawrrell@yahoo.com' gawrrell says:

    Once you publish the website on IIS it doesn’t work anymore.

  • thalesrdias@gmail.com' thales dias says:

    hi there, great article!
    Is there a way i can put a text box where user can type a text and this text is exported to a .txt file?
    I wanted to do that so i can make my ps script to read the content of this txt file

  • friend.b4usmile@gmail.com' Fariz says:

    Thank you for this article jeff. I have tried this example, I have some issues.

    From powershell I can execute the following commands with successful results:
    Get-Date
    Get-Version (AppAssure command)

    These commands are tried in windows forms application also, I got success.

    But in ASP.net I am getting the following error.
    “Error in script : The term ‘Get-Version’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.”

  • hellnot2001@yahoo.com' Michael K says:

    Hi there. Brilliant article.
    I using this Automation to run a PowerShell script in SharePoint that Checks in and publish multiple documents all at once. This assembly works great in my development environment with no problem.

    But once i’ve deployed the web application on another server (out UAT, Authoring machines), there seems to be a problem. The error i’m catching is:
    “The type initializer for ‘System.Management.Automation.SessionStateScope’ threw an exception.”

    I can see the dlls are all in gac and they are also in the bin of the application. Are you able to give more insight into this issue as i don’t know where else to look.

    Many thanks in advance.

  • nelson.wiprotech@gmail.com' Nelson says:

    Can you please help me out to execute the powershell script in the remote server by modifying your above code.

    Thanks in advance!

  • zaphodikus@hotmail.com' Conrad Braam says:

    Hi Jeff, I arrived here while looking for pointers on exposing a few methods in a powershell module via a web API and to get myself a free REST API wrapper in this way. I’d thus have my module exposed as a web API, but also be able to create a Web UI for users who don’t know any powershell at all by simply adding Models and Views. Does this sound sane? (apart from the security pain which will have to be added as a web filter)

    Now it’s my intent to only run pre-canned Powershell commands in the final tool, and unpack automation objects directly. So adding Out-String to every command is not a point for me at all (I think it sucks because it feels artificial and would mean all the existing IT guy written scripts would need out-string added to them to look pretty in the tool.). But I found a possible solution that uses a pipeline in code here:

    Basically this line of code is the clue
    Pipeline pipeline = runspace.CreatePipeline();
    ...
    pipeline.Commands.Add("Out-String");
    Collection results = pipeline.Invoke();

    Hope it helps.

    P.S. For all people struggling, powershell32bit and 64-bit are completely separate, separate settings, separate snapins, and separate security. If stuck, try both.

  • hector.varon@outlook.com' Hector Varon says:

    Hi,

    I would like complete some values in a PS1.

    end user provide this info when press execute complete the ps1 and execute.

    can I use shell.comands?

    Do you know a reference library than help me

    thanks?

  • awshuaj@gmail.com' Josh Taylor says:

    For those running into problems running a PS1. Your issue may be that you are not loading a file, but rather executing the PowerShell command “c:\some path\myscript.ps1″. Therefore, you must call the PS1 in the same way you would call it from within the PowerShell console. e.g. try using Shell.Commands.AddScript(“& ‘c:\some path\myscript.ps1′”); You can also then pass parameters to your script like Shell.Commands.AddScript(“& ‘c:\some path\myscript.ps1′ -myparam myvalue”);

  • partyholes@gmail.com' David says:

    Hey Jeff – i know this is an old thread, but thanks a lot.

    I’m struggling with getting UNC paths to work in this though. I’m trying to access the filesystem of a remote PC, but it never seems to work.

    I’ve traced it down to the “$” sign being the culprit.

    gci “\\hostname\c$\ProgramData\SubFolder” | Out-String ##fails (double quotes)
    gci ‘\\hostname\c$\ProgramData\SubFolder’ | Out-String ##fails (single quotes)
    gci “\\hostname\c`$\ProgramData\SubFolder” | Out-String ##fails (double quotes with backtick on $)
    gci “//hostname/c$/ProgramData/SubFolder” | Out-String ##fails (forward slashes)

    All of the above work in PowerShell natively.

    A share to the same location will work however:
    gci “\\hostname\SubFolder” | Out-String

    any ideas? are there some escape characters coming into play here?

    • Jeff Murr says:

      The ` symbols should work just before the dollar sign since it is a powershell reserved character. That character treats the next character as a literal even if it is a reserved symbol. Give it a try and see what happens.

    • vladimir.nikotin@outlook.com' Vladimir Nikotin says:

      was it a magic quotes issue?
      one should use single quotes for first gci argument string:
      gci ‘\\host\HiddenShare$\Still-a-string-Constant\becauseInSingleQuotes’
      instead of
      gci “\\host\HiddenShare$\PoshThinksItsaVariable”

      excuse me for my english. here is another example:
      $quotes = ‘magic’;
      Write ‘Single $quotes’;
      # output: Single $quotes
      Write “Double $quotes”;
      # output: Double magic

  • Any idea on how I could pass a string variable to a script from an input box?

    If my script has something like $strComputer = “ComputerName” I’d like the user to put in a computer name and the ComputerName get replaced in the script or passed to the script.

  • deenu.andy@gmail.com' Dinesh Sharma says:

    Hi Jeff,

    Great post! Can you please help me with a Powershell command to search the registry for a Installed S/W (MSI). Like “Firefox” should return the installed version, date etc.

    Thanks,
    Dinesh

  • jason.schuster@internode.on.net' Jason says:

    Hi,
    This works well (when I’m using the Command text box)

    However, when I try to run a script, it works find during testing (using start) However when I deploy the App to a website, The script will not run.
    ie, on the same box test works however running the deployed website does not.
    the ExecutionPolicy is set to unrestricted

  • ramvashista121@gmail.com' Ram says:

    Hi Jeff,

    Got your article after lots of search. Its very helpful and now I am hoping that my requirement can be achieved.
    I have to create one C# class that will call a powershell file (.ps1) placed on another server. Could you share your thoughts on this plz.

    Regards,
    Ram

  • john.zhang@189CSP.com' John Zhang says:

    Hey Jeff, great article!
    I come from China ,I am sorry to bother you.
    I have a problem when run a powershell script ,the error is that the executionpolicy is restricted but i have set my shell excutionpolicy as unrestricted mode in my computer.

    Many thanks in advance.

  • itwork4me@yahoo.com' matt says:

    Gentle folks of all bathrooms…the instructions on this are fine. However the folks commenting may not understand why some commands work and some dont.
    If you get you app built (I used vs 2010 and 3.5 framework – so I didn’t have to worry about removing references i.e. Linq).
    Once deployed, you will want to configure your IIS apppool to not load a profile. Unless you have one for the user that is running the app pool, you may not be aware of your default location when you run your commands.

    So…First run $env.useename on the built sameples InputTxt.
    You will probably find it is your machine name and not a user you intended.
    Also, typing set-location &’\\path\pathey\path’ and then ls will set your location and reutn a list of filrs for that one time you press execute and the PS object is created.

    I added

    shell.Commands.AddScript (“set-location &’\\servername\drive\folder’”)
    shell.Invoke ();

    Before the Add script line for the input .Text

    I’d be curious if this resolves any issues

  • rage_a_holic@hotmail.com' Brian says:

    Thanks for the excellent how-to, Jeff. Works like a charm and was able to figure out how to pass variables from ASP.NET back to the script.

    Really appreciate you taking the time to put this together and share.

  • o-js@live.com' Ory says:

    Hey Jeff, First of all awesome article, thank you very much for taking your time to share this cool information !

    i got a quick question if you have a moment to help me out,
    i tried to get the feed-back posted from the script to be real time (i have a big script and i want the output to be real time to give the user indication of what is going on – as opposed only getting feedback when the final results are in/script finished running.) and i cant seem to get it to work, any chance to help me out?

    • Jeff Murr says:

      Unfortunately, this is a limitation of forms based asp.net. To do something where you get repeated status updates you’ll need to create a client side JavaScript to repeatedly call a server side endpoint. Very possible, just something a bit more involved than using a button and textbox control. Glad you found the article helpful!

  • […] As well as providing a scripting environment, PowerShell can be embedded into an application by using System.Management,Automation , so that the user of the application can extend it via scripts. You can even do this in ASP.NET […]

  • workspaced@outlook.com' Grant W. says:

    Jeff, this has been a great resource in launching my own similar-themed (for HR) site. One question, and if you’ve already answered it my apologies.

    What would it take for me to be able to use that input textbox for an entire powershell script? for example:

    $test = Get-Service | Out-String
    $test

    As it is now, it processes each line individually, meaning the above won’t work as it would in a PS window, but I’d like it to process the entire box as a whole. Would you point me in the right direction?

    • Jeff Murr says:

      Thank you! I would try to build your commands and use them as a single script block of an Invoke-Command cmdlet. The same sycronis execution would occur unless you created run spaces or jobs but that’s probably over doing it for your request. Remember to also creat an array of any variables and pass them as your arguments array. Good luck!

  • mohammadrezamp@gmail.com' mohammadreza says:

    hello
    i have window dns server and i try add domain with this command>>
    Add-DnsServerPrimaryZone -Name “MyDomain.com” -ZoneFile “MyDomain.com.dns” -DynamicUpdate “none”
    Add-DnsServerResourceRecord -ZoneName “MyDomain.com” -A -Name “www” -IPv4Address “192.168.100.2″
    Add-DnsServerResourceRecord -ZoneName “MyDomain.com” -A -Name “@” -IPv4Address “192.168.100.2″

    it’s work on powershell directly but it’s not work on this webpage

    could you please help me,how i can run this command on webpage for add domain to dns server

    thank you

  • amitsharma.vgi@gmail.com' Amit says:

    hello jeff

    I am using dropdown instead of textbox to show multiple scripts on my machine.

    DirectoryInfo di = new DirectoryInfo(@”D:\Test\”);
    //InputDropDownList.DataSource = di.GetFiles();
    //InputDropDownList.DataTextField = “Name”;
    //InputDropDownList.DataValueField = “FullName”;
    //InputDropDownList.DataBind();

    I have this code in pageload method used for binding dropdown. its working fine but on selecting in dropdown its passing only 1st script.

  • ernie@mikulic.com' Ernie M. says:

    Nice work. Was able to get the basic setup going in Windows Server 2016 with IIS10 and Visual Studio Community Ed 2017.
    I ran code inline like you showed and ran a script (function as script) just fine.
    Working on the next level of passing arguments (parameters) to a script .

  • chanh.hua@capgroup.com' Chanh Hua says:

    It requires the appPool Identity to have administrator right. Does anyone have know to get around this so that the web app can be hosted in Azure cloud?

  • h.j.huls@tmdi.nl' Harald says:

    Hello Jeff,
    Great article! I have created it with a local powershell script. When I debug on my system it runs great. Now I have released it to IIS and I cannot get it to work. Everything seems to be fine, but when I click on the button nothing happens. Execution policy both on unrestricted. Do you have any idea? Is in in the application pool? How should I run this ‘as admin’?

  • jakub.dudek@ig.com' Jakub says:

    This is faaking tremendous mate, thank you for that article.
    Now sky’s the limit for my department :)

  • […] Execute PowerShell from a ASP.NET Web Application. – I had an interesting request come in to automate existing server-side PowerShell processes that have been initiated by server admins thus far locally on. […]

  • […] Execute PowerShell from a ASP.NET Web Application. – I had an interesting request come in to automate existing server-side PowerShell processes that have been initiated by server admins thus far locally on. […]

  • turbozmike@yahoo.com' Mike says:

    Anyone using this have it break in the last week or so?
    I am no longer able to invoke powershell.
    shell.invoke(); from this example no longer works for me on multiple machines.

  • […] started with this post from Jeff Murr, which detailed how to use asp.net to call a PowerShell script, and return some output. This really […]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>