Aspram
Aspram

Reputation: 653

Start-Process is not recognized when running powershell script from C# code

I have the following code which stops IIS Application pool by executing Powershell script:

        using (PowerShell ps = PowerShell.Create())
        {
            ps.AddScript("Set-ExecutionPolicy -Scope LocalMachine Unrestricted");
            string stopCommand = File.ReadAllText($"{scriptPath}StopIISPool.ps1");                
            ps.AddScript(stopCommand);
            ps.AddScript($"StopIISAppPool -StopScriptPath {scriptPath}IISStopCommand.ps1 -poolName {paths.IISAppPoolName}");
            ps.Invoke();

            Collection<ErrorRecord> errors = ps.Streams.Error.ReadAll();
        }

And here StopIISPool.ps1 contains the following powershell script:

    function StopIISAppPool
    {
        Param(
        [parameter(Mandatory=$true)]
        [string]$stopScriptPath,
        [parameter(Mandatory=$true)]
        [string]$poolName
        )
        process
        {
            PowerShell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "&  {Start-Process PowerShell -windowstyle hidden -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -noexit -File $stopScriptPath -poolName $poolname' -Verb RunAs}";
        }
   }

And here stopScriptPath is the path of the following command which executes without errors only with elevated permissions:

    Param(
        [parameter(Mandatory=$true)]
        [string]$poolName
    )
    Stop-WebAppPool -Name $poolName;

The above C# code runs in ASP.NET Core application. When I deploy the application under IIS on Windows Server 2012 R2 and run I get the following error on ps.Invoke() line:

Start-Process is not recognized as the name of a cmdlet, function, script file, or operable program.

Could someone please explain why I get that error?

Upvotes: 2

Views: 5694

Answers (1)

Aspram
Aspram

Reputation: 653

I have solved this issue. Actually I have found a workaround. For manipulating IIS Application pools I switched to windows Command Line instead of PowerShell. I have used the following command:

    C:\Windows\System32\inetsrv\appcmd start apppool /apppool.name:$poolName.

Upvotes: 1

Related Questions