Skip to main content

PowerShell script to remotely start, stop, or restart an IIS Application Pool.

[CmdletBinding()]
param(
    # The App Pool name.
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [String]
    $Name,

    # The App Pool operation to perform. Accepted values are 'Start', 'Stop', or 'Restart'.
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [ValidateSet('Start', 'Stop', 'Restart')]
    [String]
    $Operation,

    # The PSSession to use for connecting to the server running IIS.
    [Parameter(Mandatory = $true)]
    [System.Object]
    $Session
)

$job = Invoke-Command -Session $Session -ScriptBlock {
    Import-Module WebAdministration

    $command = "{0}-WebAppPool" -f $using:Operation

    & $command -Name "$using:Name"
} -AsJob

$job | Wait-Job
$job | Remove-Job

# -------------------------------------------------
# Example usage
# -------------------------------------------------

# $server = '<server_name>'
# $username = '<username>'
# $password = ConvertTo-SecureString '<password>' -AsPlainText -Force
# $credential = New-Object System.Management.Automation.PSCredential($username, $password)
# $session = New-PSSession -ComputerName $server -Credential $credential
# .\IISAppPool.ps1 -Name 'MyAppPool' -Operation 'Restart' -Session $session
# Remove-PSSession $session