DevilWAH
DevilWAH

Reputation: 2633

c#.net remote powershell for iis

Hi I have the following bit of code

 //set up exchange server name
        var Exchangesrv = "ex1.iah.ac.uk";


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

        // Add the script to the PowerShell object
        shell.Commands.AddScript("Invoke-Command -Computername hostname.example.com -ScriptBlock{get-alias}");

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


        Input.DataSource = results;
        Input.DataBind();

So very simply I want to invoke a power shell command and the "input" is a list box object I am populating

But When i run it on the IIS server it does not work, I think it is because the IIS application is not running with an account that is admin on the remote server I am trying to run the command against. Can any one help resolving this. How can I get the webpage to call this invoke command with the right credentials?

Edit
So i decided to create a profile on the web server that means when the account that I am using opens power-shell the exchange module is loaded. But I don't see this loading when using the following code

using (var powershell = PowerShell.Create())
        {
            //powershell.Runspace = runspace;


            // Add the script to the PowerShell object
            //powershell.AddScript("Get-alias");
            powershell.AddScript("Get-DynamicDistributionGroup");


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


            Input.DataSource = results;
            Input.DataBind();

So What should be happening is power shell runs locally on the web server, but i need it to load the profile however I cant see why it is not doing it. Is there a command to force it to load the moduel.

Upvotes: 0

Views: 459

Answers (2)

Peter Joder
Peter Joder

Reputation: 11

The property on the application pool is "Load User Profile". This must be set to True.

I can't tell anyone why this is, but it solved my Access denied issue.

More about the property here: https://blogs.msdn.microsoft.com/vijaysk/2009/03/08/iis-7-tip-3-you-can-now-load-the-user-profile-of-the-application-pool-identity/

Upvotes: 1

DevilWAH
DevilWAH

Reputation: 2633

In the end the impersonating and invoking did not do the trick (I could have used invoke but I did not want credentials in the code)

I found I had to change the properties on the application pool and then it worked fine.

Upvotes: 0

Related Questions