IIS:\\AppPools appears to be empty when used from inside application pool

Viewed 1610

I am trying to run a PowerShell script to set some properties on an IIS application pool. The script works fine when I run it from the PowerShell application. However, it does not work when running from inside an IIS application pool.

The script looks as follows:

import-module webadministration

$WebSiteName = "MyWebsite"
$WebSiteFullName = "IIS:\Sites\" + $WebSiteName
$ApplicationPool = Get-Item $WebSiteFullName | Select-Object applicationPool
$ApplicationPoolFullName = "IIS:\AppPools\" + $ApplicationPool.applicationPool

Add-WebConfiguration -filter '/system.applicationHost/serviceAutoStartProviders' -value (@{name="ApplicationPreload";type="MyApplication.ApplicationPreload, MyApplication"})

set-itemproperty $WebSiteFullName -name applicationDefaults.serviceAutoStartEnabled -value True
set-itemproperty $WebSiteFullName -name applicationDefaults.serviceAutoStartProvider -value 'ApplicationPreload'

set-itemproperty $ApplicationPoolFullName -name autoStart -value True
set-itemproperty $ApplicationPoolFullName -name startMode -value 1 # 1 = AlwaysRunning

Its purpose is to make an ASP.NET application using Hangfire always running, as described here: http://docs.hangfire.io/en/latest/deployment-to-production/making-aspnet-app-always-running.html

The script runs fine when run in the PowerShell application.

However, when it from the ASP.NET application using System.Management.Automation, the last two lines fail. The error message is:

Cannot find path 'IIS:\\AppPools\\fwsetupsite' because it does not exist.

As a test, I added a line

dir IIS:\AppPools > c:\apppools.txt

which produces an empty file c:\apppools.txt if run from the ASP.NET application, but correctly dumps the names of all application pools into the file when run from the PowerShell application. So it seems that IIS:\\AppPools is empty.

The C# code which runs the script from within the ASP.NET application looks as follows:

using (PowerShell shell = PowerShell.Create())
{
    string script = File.ReadAllText(FilePath);
    shell.AddScript(script);
    shell.Invoke();
}
1 Answers
Related