marwaha.ks
marwaha.ks

Reputation: 549

Restarting App Pool via c# using powershell script

I'm trying to restart an iis app pool on a remote server. First I would like to stop the app pool however I am getting an

Cannot convert the "{ Stop-WebAppPool -Name "BaymentPool" }" value of type "System.String" to type "System.Management.Automation.ScriptBlock".

exception

public void StopAppPool()
    {
        Runspace runSpace = RunspaceFactory.CreateRunspace();
        runSpace.Open();

        Pipeline pipeline = runSpace.CreatePipeline();

        Command invokeCmd = new Command("Invoke-Command");
        invokeCmd.Parameters.Add("ComputerName","IISC02");
        invokeCmd.Parameters.Add("ScriptBlock","{ Stop-WebAppPool -Name \"BaymentPool\" }");
        pipeline.Commands.Add(invokeCmd);


        Collection<PSObject> output = pipeline.Invoke();
        foreach (PSObject psObject in output)
        {
            Process process = (Process)psObject.BaseObject;
            Console.WriteLine("Process name: " + process.ProcessName);
        }
    }

I can't quite fathom out what I am doing wrong. I know I need to add each param separately, which I think I'm doing, however it still complains.

Upvotes: 4

Views: 659

Answers (2)

DevGuru
DevGuru

Reputation: 156

A simple solution could be:

var serverManager = ServerManager.OpenRemote("000.000.000.000"); // Ip Address of Remote server

            var appPool = serverManager.ApplicationPools["MyAppPool"];

            if (appPool == null) return;

            if (appPool.State == ObjectState.Stopped)
            {
                appPool.Start();
            }
            else
            {
                appPool.Recycle();
            }

Upvotes: 3

Mikael Nitell
Mikael Nitell

Reputation: 1129

The scriptblock parameter should be of type ScriptBlock

invokeCmd.Parameters.Add("ScriptBlock", ScriptBlock.Create("{ Stop-WebAppPool -Name \"BaymentPool\" }"));

Your code that checks result is not correct, that cast to a Process object will not work. Have a look here for examples of how to inspect the result of your invoke: http://blogs.msdn.com/b/kebab/archive/2014/04/28/executing-powershell-scripts-from-c.aspx

Upvotes: 3

Related Questions