4

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.

2 Answers 2

3

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(); } 
Sign up to request clarification or add additional context in comments.

Comments

3

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

4 Comments

Great. After adding "ScriptBlock.Create(", I do not get an exception anymore, however,my app pool is not stopped.
@Kam what do you get? What is the output of the pipeline? Are you getting error messages?
@PanagiotisKanavos output = Count = 0. No error messages
Just a quick question, would i need to pass in credentials or will it use AD?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.