How to start and stop application pool in IIS using powershell script
Asked Answered
N

10

28

I want to start and stop application pool in IIS using powershell script. I had try to write the script but i didn't get this.

Narcotize answered 13/4, 2016 at 13:10 Comment(0)
J
39

You can use this

if your use (PowerShell 2.0) import WebAdministration module

import-module WebAdministration

Please check the state of the application pool before. If the application pool is already stopped you get an exception.

Stop application pool:

$applicationPoolName = 'DefaultAppPool'

if((Get-WebAppPoolState -Name $applicationPoolName).Value -ne 'Stopped'){
    Write-Output ('Stopping Application Pool: {0}' -f $applicationPoolName)
    Stop-WebAppPool -Name $applicationPoolName
} 

Start application pool:

if((Get-WebAppPoolState -Name $applicationPoolName).Value -ne 'Started'){
    Write-Output ('Starting Application Pool: {0}' -f $applicationPoolName)
    Start-WebAppPool -Name $applicationPoolName
}

Permissions: You have to be a member of the "IIS Admins" group.

Jasisa answered 4/6, 2017 at 8:17 Comment(3)
Additional to this, your app pool can fail to start of it is still Stopping. The transition from Started to Stopped is not instant so you may need to add some timeouts/sleeps into your scripts to account for this.Mendelson
This are two different scripts. First you run stop, then you make any work with web application, then you run second one.Overtly
If you need to have the command blocking until the action is actually performed, you may use appcmd instead. You still have to check the state of your pool prior to calling it, so you may combine both the applet and the command line. I have added an answer doing that, for those who need it.Persistent
M
23

These days the IISAdminstration module has mostly superceded WebAdministration.

So if you're on Windows 10 / Server 2016, you can use Get-IISAppPool like this:

Import-Module IISAdministration
(Get-IISAppPool "name").Recycle()
Maloney answered 4/6, 2017 at 9:3 Comment(2)
THIS is correct!Deracinate
For the actual request of the OP, which is not recycle but start and stop, use Start() and Stop() instead of Recycle(). These commands return immediately without waiting for the action to be actually completed, which may cause issues depending on your use case.Persistent
S
10

To stop an App Pool using PowerShell use

Stop-WebAppPool -Name YourAppPoolNameHere

And to start the App Pool

Start-WebAppPool -Name YourAppPoolNameHere

You will need the WebAdministration module installed so check you have it with this command

 Get-Module -ListAvailable
Snorkel answered 26/5, 2017 at 8:56 Comment(1)
for all of them Get-IISAppPool | Start-WebAppPoolSizing
C
4

I use the following code in an Azure pipeline:

Stop the pool:

Import-Module -Name 'C:\Windows\System32\WindowsPowerShell\v1.0\Modules\WebAdministration\WebAdministration.psd1';

$AppPoolName = 'DefaultAppPool';
$AppPoolState = (Get-WebAppPoolState -Name $AppPoolName).Value;
$WasStarted = $false;
$Timeout = [System.TimeSpan]::FromMinutes(1);
$StopWatch = New-Object -TypeName 'System.Diagnostics.Stopwatch';
$StopWatch.Start();
# Possible status: "Starting", "Started", "Stopping", "Stopped" and "Unknown".
while ($AppPoolState -ne 'Stopped') {
  if ($AppPoolState -eq 'Started') {
    $WasStarted = $true;
    Stop-WebAppPool -Name $AppPoolName;
  }
  Start-Sleep -Seconds 2;
  if ($StopWatch.Elapsed -gt $Timeout) {
    throw New-Object -TypeName 'System.TimeoutException' -ArgumentList "Timeout of $($Timeout.TotalSeconds) seconds exceeded!";
  }
  $AppPoolState = (Get-WebAppPoolState -Name $AppPoolName).Value;
}

Start the pool:

Import-Module -Name 'C:\Windows\System32\WindowsPowerShell\v1.0\Modules\WebAdministration\WebAdministration.psd1';

$AppPoolName = 'DefaultAppPool';
$AppPoolState = (Get-WebAppPoolState -Name $AppPoolName).Value;
$WasStopped = $false;
$Timeout = [System.TimeSpan]::FromMinutes(1);
$StopWatch = New-Object -TypeName 'System.Diagnostics.Stopwatch';
$StopWatch.Start();
# Possible status: "Starting", "Started", "Stopping", "Stopped" and "Unknown".
while ($AppPoolState -ne 'Started') {
  if ($AppPoolState -eq 'Stopped') {
    $WasStopped = $true;
    Start-WebAppPool -Name $AppPoolName;
  }
  Start-Sleep -Seconds 2;
  if ($StopWatch.Elapsed -gt $Timeout) {
    throw New-Object -TypeName 'System.TimeoutException' -ArgumentList "Timeout of $($Timeout.TotalSeconds) seconds exceeded!";
  }
  $AppPoolState = (Get-WebAppPoolState -Name $AppPoolName).Value;
}

The variables $WasStarted and $WasStopped are extra information not used within this examples but could be used to determine whether an application pool should be restarted after the deployment of a new version is completed or not (because it was already stopped before).

Callow answered 8/9, 2021 at 16:50 Comment(0)
E
3

You can stop and stop all application pools respectively using the following powershell script. The second line below elevates permissions. You could exclude this and just run as administrator.

Stop all application pools script

Import-Module WebAdministration

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }

$AppPools=Get-ChildItem IIS:\AppPools | Where {$_.State -eq "Started"}

ForEach($AppPool in $AppPools)
{
 Stop-WebAppPool -name $AppPool.name
# Write-Output ('Stopping Application Pool: {0}' -f $AppPool.name)
}

Start all application pools script

  Import-Module WebAdministration

    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }

    $AppPools=Get-ChildItem IIS:\AppPools | Where {$_.State -eq "Stopped"}
    ForEach($AppPool in $AppPools)
    {
     Start-WebAppPool -name $AppPool.name
    # Write-Output ('Starting Application Pool: {0}' -f $AppPool.name)
    }
Emylee answered 13/3, 2019 at 14:27 Comment(1)
This worked great to ensure it's running as an admin, but you can replace everything else with: Get-IISSite | Select-Object Name | Start-IISSite and Get-IISSite | Select-Object Name | Stop-IISSite if you have access to IISAdminstrationFruge
C
2

You have to import the WebAdministration module using Import-Module and then you can use Start-WebAppPool and Stop-WebAppPool

Coltish answered 13/4, 2016 at 13:14 Comment(3)
That´s a permission problem. Try touse a administrator profile.Jasisa
You can get an error if the application pool is stopped and you try to stop them. Execute this twice Stop-WebAppPool -Name "DefaultAppPool"Jasisa
Since (PowerShell 3.0) you don´t need to import modules.Jasisa
T
1

I ended up with something like this:

Stopping the app pool:

    - task: PowerShell@2
      displayName: Stop App Pool
      inputs:
        targetType: 'inline'
        script: |
          $applicationPoolName = '$(MySite)AppPool'

          if((Get-WebAppPoolState -Name $applicationPoolName).Value -ne 'Stopped')
          {
           Write-Output ('Stopping Application Pool: {0}' -f $applicationPoolName)
           Stop-WebAppPool -Name $applicationPoolName
           Start-Sleep -Seconds 2
          } 

Starting the app pool:

- task: PowerShell@2
  displayName: Start App Pool
  inputs:
    targetType: 'inline'
    script: |
      $applicationPoolName = '$(MySite)AppPool'

      if((Get-WebAppPoolState -Name $applicationPoolName).Value -ne 'Started')
      {
        Start-Sleep -Seconds 2
        Write-Output ('Starting Application Pool: {0}' -f $applicationPoolName)
        Start-WebAppPool -Name $applicationPoolName
      }
Tyrus answered 16/3, 2023 at 10:14 Comment(0)
B
0

From microsoft doc. https://learn.microsoft.com/en-us/powershell/module/webadminstration/restart-webapppool?view=winserver2012-ps

Restart-WebAppPool recycles an application pool.
Then you don't have to think of a stop, wait, and start.

Import-Module WebAdministration

For a specific running AppPool

$applicationPoolName = 'DefaultAppPool'
Get-ChildItem IIS:\AppPools | Where {$_.State -ne "Stopped" -and $_.name -eq $applicationPoolName} | Restart-WebAppPool

For all running AppPools

Get-ChildItem IIS:\AppPools | Where {$_.State -ne "Stopped"} | Restart-WebAppPool
Blus answered 9/3, 2021 at 11:42 Comment(0)
Z
0

Like mentioned by Mitch Pomery in the comments, the apppool does not stop instantly. Because of this, my CI script failes to copy files into the directory that was still being used by the apppool. Instead, I reverted back to appcmd tool (which apparently waits for the apppool to actually stop), but still used WebAdministration module to check if the pool is running.

Import-Module WebAdministration
if ((Get-WebAppPoolState -Name PCSServer).Value -ne 'Stopped'){ C:\Windows\system32\inetsrv\appcmd stop apppool "PCSServer-WS" }
Expand-Archive -Path MBE.zip -DestinationPath $DEPLOY_PATH -Force
C:\Windows\system32\inetsrv\appcmd start apppool "PCSServer-WS"
Zo answered 2/3, 2022 at 9:7 Comment(0)
H
0

As stated by this answser, the IISAdminstration module has mostly superseded WebAdministration. (See here for the object model IISAdminstration returns.)

For scripts that checks the state of the pool before acting on it as advised by this answer, and that waits for the action to be actually done (solution taken here), use these:

Stop application pool:

$applicationPoolName = 'DefaultAppPool'

if ((Get-IISAppPool -Name $applicationPoolName).State -ne 'Stopped') {
  Write-Output ('Stopping Application Pool {0}' -f $applicationPoolName)
  & $env:windir\system32\inetsrv\appcmd.exe stop apppool /apppool.name:"$applicationPoolName"
}

Start application pool:

$applicationPoolName = 'DefaultAppPool'

if ((Get-IISAppPool -Name $applicationPoolName).State -ne 'Started') {
  Write-Output ('Starting Application Pool {0}' -f $applicationPoolName)
  & $env:windir\system32\inetsrv\appcmd.exe start apppool /apppool.name:"$applicationPoolName"
}

In my, case, I needed the stop action as an Azure pipeline task, which I have defined as this:

# Stops an application pool without failing if it is already stopped. https://mcmap.net/q/486963/-how-to-start-and-stop-application-pool-in-iis-using-powershell-script
parameters:
- name: poolName
  displayName: 'Application pool name'
  type: string
steps:
- task: PowerShell@2
  displayName: 'Stop application pool'
  inputs:
    targetType: inline
    script: |
      # IISAdministration : https://learn.microsoft.com/en-us/powershell/module/iisadministration/
      # And for objects it returns: https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.administration
      if ((Get-IISAppPool -Name '${{ parameters.poolName }}').State -ne 'Stopped') {
        Write-Output ('Stopping Application Pool {0}' -f '${{ parameters.poolName }}')
        # Stop() on the pool returns without waiting for the pool to be actually stopped. appcmd waits.
        # https://mcmap.net/q/503070/-how-to-ensure-iis-website-is-completely-stopped-in-powershell
        & $env:windir\system32\inetsrv\appcmd.exe stop apppool /apppool.name:"${{ parameters.poolName }}"
      }
    failOnStderr: true
...

Hexapla answered 29/7 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.