Skip to content

Instantly share code, notes, and snippets.

@ismits
Created September 24, 2019 16:47
Show Gist options
  • Save ismits/d77eab10ba622c8acfdfe15fa1694788 to your computer and use it in GitHub Desktop.
Save ismits/d77eab10ba622c8acfdfe15fa1694788 to your computer and use it in GitHub Desktop.
Configure IIS AppPool Max Memory via PowerShell
function Configure-IISAppPoolMaxMemory([string]$AppPoolName = "ApplicationPoolDefaults",
[int]$MaxMem = 20)
{
[int]$ExitCode = 0
# Ensure WebAdministration module is loaded.
if ((Get-Module -Name WebAdministration) -eq $null)
{
Write-Log "Importing module: WebAdministration"
Import-Module -Name WebAdministration -ErrorAction SilentlyContinue | Write-Log
if ((Get-Module -Name WebAdministration) -eq $null)
{
Write-Log -IsError "Error: Unable to import module: WebAdministration"
$ExitCode = 1
return $ExitCode
}
}
# Percentage
if ($MaxMem -gt 0 -and $MaxMem -lt 100)
{
Write-Log "Setting maximum memory to $($MaxMem)% of total system memory."
$ComputerSystem = Get-WmiObject -Class Win32_ComputerSystem
$SystemMemMb = [System.Math]::Round($ComputerSystem.TotalPhysicalMemory/(1024*1024))
Write-Log "System memory: $($SystemMemMb)MB"
$MaxMemMb = [System.Math]::Floor(($SystemMemMb*$MaxMem)/100)
Write-Log "Setting maximum memory to $($MaxMemMb)MB."
}
# Unlimited
elseif ($MaxMem -eq 0)
{
$MaxMemMb = 0
Write-Log "Setting maximum memory to 0 (unlimited)."
}
# MB value
else
{
$MaxMemMb = $MaxMem
Write-Log "Setting maximum memory to $($MaxMemMb)MB."
}
# ApplicationPoolDefaults is a special case
if ($AppPoolName -eq "ApplicationPoolDefaults")
{
$ConfigurationFilter = "/system.applicationHost/applicationPools/applicationPoolDefaults/recycling/periodicRestart"
}
else
{
$ConfigurationFilter = "/system.applicationHost/applicationPools/add[@name='$AppPoolName']/recycling/periodicRestart"
}
$Property = Get-WebConfigurationProperty -Filter $ConfigurationFilter -Name "privateMemory"
if ($Property -ne $null)
{
[System.Int64]$CurrentMaxMemKb = $Property.Value
[System.Int64]$NewMaxMemKb = $MaxMemMb*1024
if ($CurrentMaxMemKb -ne $NewMaxMemKb)
{
Write-Log "Changing Private Memory Limit (KB) configuration property value from $($CurrentMaxMemKb) to $($NewMaxMemKb)."
Set-WebConfigurationProperty -Filter $ConfigurationFilter -Name "privateMemory" -Value $NewMaxMemKb
}
else
{
Write-Log "The Private Memory Limit (KB) configuration property is already set to the specified value: $NewMaxMemKb"
}
}
else
{
Write-Log -IsError "Unable to find privateMemory configuration property at: $ConfigurationFilter"
$ExitCode = 2
}
return $ExitCode
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment