Calling Powershell scripts from C# to monitor IIS Application pool
Hi All,
I recently had a requirement to monitor an application pool in one of our server and if it is gets stopped for some odd reason it must be restarted automatically.
I created a windows application to achieve this task. The following are two methods which I used to check the status and if it is stopped to start the application pool.
private string GetpoolStatus(string computerName,string appPoolName)
{
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();
string result = "";
ScriptBlock scriptBlock = ScriptBlock.Create("Import-Module WebAdministration; Get-WebAppPoolState -NAME " + appPoolName + "");
command.AddCommand("Invoke-Command").AddParameter("ComputerName", computerName).
AddParameter("ScriptBlock", scriptBlock);
powershell.Commands = command;
try
{
runspace.Open();
powershell.Runspace = runspace;
Collection<PSObject> output = powershell.Invoke();
Collection<ErrorRecord> errors = powershell.Streams.Error.ReadAll();
PSObject pSObject = output.FirstOrDefault();
if(pSObject != null)
{
var vMember = pSObject.Members.FirstOrDefault(m => m.Name == "Value");
return vMember.Value.ToString();
}
if (errors != null && errors.Count > 0)
{
foreach (ErrorRecord er in errors)
{
result += er.Exception.ToString() + Environment.NewLine;
}
}
}
catch (Exception ex)
{
result = ex.Message.ToString();
}
finally
{
runspace.Dispose();
runspace = null;
powershell.Dispose();
powershell = null;
}
return result;
}
private bool StartPool(string computerName, string appPoolName)
{
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();
string result = "";
ScriptBlock scriptBlock = ScriptBlock.Create("Start-WebAppPool -Name " + appPoolName + "");
command.AddCommand("Invoke-Command").AddParameter("ComputerName", computerName).
AddParameter("ScriptBlock", scriptBlock);
powershell.Commands = command;
try
{
runspace.Open();
powershell.Runspace = runspace;
Collection<PSObject> output = powershell.Invoke();
Collection<ErrorRecord> errors = powershell.Streams.Error.ReadAll();
if (errors != null && errors.Count > 0)
{
return false;
}
}
catch (Exception ex)
{
result = ex.Message.ToString();
}
finally
{
runspace.Dispose();
runspace = null;
powershell.Dispose();
powershell = null;
}
return true;
}
Comments
Post a Comment