Joel WZ
Joel WZ

Reputation: 100

Executing Powershell script from Websocket svia c# to stop/start website

We have a need to remotely start/stop IIS websites and app pools, so we can remotely deploy a website. I have a Websocket app that starts a PowerShell script to complete these activities. I built Powershell scripts to complete that tasks and they work perfectly in the Powershell prompt. However, when I try to run these scripts from the websocket, the scripts run (I have Write-Outputs in the scripts), but nothing happens the site and pool do not change. I don't see anything that says it failed, either. I would appreciate any help that can be given.

Below is an excerpt from the code:

using (PowerShell ps = PowerShell.Create())
{
    string scriptContent = string.Empty;
    string pathToReadScriptFile = string.Empty;
    // add a script that creates a new instance of an object from the caller's namespace
    if (r.StartStop.ToLower() == "stop")
    {
        pathToReadScriptFile = Path.Combine(scriptsPath, "StopPoolAndSite.ps1");
    }
    else
    {
        pathToReadScriptFile = Path.Combine(scriptsPath, "StartPoolAndSite.ps1");
    }

    using (StreamReader sr = new StreamReader(pathToReadScriptFile))
    {
        scriptContent = sr.ReadToEnd();
        sr.Close();
    }

    ps.AddScript(scriptContent);
    ps.AddParameter("siteName", r.SiteName);
    ps.AddParameter("poolName", r.PoolName);

    // invoke execution on the pipeline (collecting output)
    Collection<PSObject> PSOutput = ps.Invoke();

    // loop through each output object item
    foreach (PSObject outputItem in PSOutput)
    {
        if (outputItem != null)
        {
            await SendMessageToAllAsync($"{outputItem.ToString()}");
        }
    }
}

Here is one of the powershell script code:

Param(
 [Parameter(Mandatory=$True)]
 [string]$siteName ,
 [string]$poolName
     )

if (-Not $poolName)
{
$poolName = $siteName
Write-Output "PoolName not supplied.  Using $siteName as default. "
} 

Import-Module WebAdministration
Write-Output "Preparing to Start AppPool: $poolName"
Write-Output "(OutPut)Preparing to Start AppPool: $poolName"
Start-WebAppPool  $poolName 

Write-Output "Preparing to Start Site: $siteName"
Start-WebSite  $siteName 
Get-WebSite  $siteName 

Upvotes: 0

Views: 178

Answers (1)

Eldar
Eldar

Reputation: 10790

Actually i would suggest not to reinvent the wheel there is a project for that check these out :

Upvotes: 1

Related Questions