I need to recycle an AppPool in IIS on my server when the SQL Server Service starts.
The route I am taking is to have a startup stored procedure which runs an Agent job that has a Powershell job step.
I have created / grabbed from the Internet a Powershell script which recycles the app pool:
# Load IIS module:
Import-Module WebAdministration
# Set a name of the site we want to recycle the pool for:
$site = "Default Web Site"
# Get pool name by the site name:
$pool = (Get-Item "IIS:\Sites\$site"| Select-Object applicationPool).applicationPool
# Recycle the application pool:
Restart-WebAppPool $pool
This works at the OS level but only when Powershell is run as an administrator (Even though the account I am logged into Windows as is in the Admin group)
Sure enough, if I create the job in agent with a Powershell step containing the above code, upon execution I get the error
A job step received an error at line 6 in a PowerShell script. The corresponding line is '$pool = (Get-Item "IIS:\Sites\$site"| Select-Object applicationPool).applicationPool '. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Cannot retrieve the dynamic parameters for the cmdlet. Filename: redirection.config Error: Cannot read configuration file due to insufficient permissions '. Process Exit Code -1. The step failed.
So I need a way to "Run as Administrator" from SQL Server Agent
I had success at the OS level creating a new script which runs the original script with elevated permissions:
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
# Relaunch as an elevated process:
Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
exit
}
# Now running elevated so launch the script:
& "d:\path\to\my\script.ps1"
which allows me to run the new script from either a non elevated CMD prompt or non elevated Powershell prompt. However, when i try to run from agent as either a Powershell step or CMD step I get
The machine-default permission settings do not grant Local Activation permission for the COM Server application with CLSID {longguidhere} and APPID {longguidhere} to the user NT SERVICE\SQLSERVERAGENT SID (longguidhere) from address LocalHost (Using LRPC) running in the application container Unavailable SID (Unavailable). This security permission can be modified using the Component Services administrative tool.
I have also tried
Start-Process powershell -Verb runAs -FilePath "d:\path\to\my\script.ps1"
which again, at the OS level worked but when run from Agent gives me the same error.
How can I get either
a: recycle the app pool without requiring elevated priveleges
or
b: run the script to recycle the app pool with elevated priveleges from SQL Server Agent?