Search code examples
c#asp.netpowershellinvoke-command

Remote powershell call using Invoke-Command doesn't work from ASP.NET


The following command works when called directly from powershell, but not when called within an ASP.NET application.

Invoke-Command -ComputerName remotesrv -ScriptBlock { 5 }

I suppose, there is some kind of user rights problem, but at this point I am stuck and don't know how to solve this.

The ASP.NET code looks as follows:

System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        using (PowerShell powershell = PowerShell.Create())
        {
            var rs = "-ComputerName remotesrv";
            powershell.AddScript("Set-ExecutionPolicy RemoteSigned");
            var script = String.Format("Invoke-Command {0} -scriptblock {{ 5 }}", rs);
            powershell.AddScript(script);

            powershell.InvocationStateChanged += delegate(object sender, PSInvocationStateChangedEventArgs e)
            {
                if (e.InvocationStateInfo.State == PSInvocationState.Completed)
                {
                    // Clean up
                }
            };

            var output = new PSDataCollection<PSObject>();
            output.DataAdded += delegate(object sender, DataAddedEventArgs e)
            {
                PSDataCollection<PSObject> myp = (PSDataCollection<PSObject>)sender;
                Collection<PSObject> results = myp.ReadAll();
                foreach (PSObject result in results)
                {
                    if (result.BaseObject is int)
                    {
                        // Do something in the database
                    }
                }
            };

            IAsyncResult asyncResult = powershell.BeginInvoke<PSObject, PSObject>(null, output);
            asyncResult.AsyncWaitHandle.WaitOne();
        }
    }
);

If I don't add -ComputerName remotesrv, the script is executed.

What do you need to do, to be able to call a powershell script remotely from an ASP.NET application?


Solution

  • I would recommend you read through the Powershell remoting requirements specifically the User Permission portion. By default, the account creating the connection must be an administrator on the remote machine. If your web application is running under an identity that is not an administrator on the remote machine, the connection will fail. Note that this is the default behaviour and can be changed by tweaking the session configurations on the remote machine.