PowerShell设置IIS应用池多回收时间仅生效首个的问题排查
问题
需要为IIS中的应用池设置两个特定回收时间(如00:15和04:30),GUI中可通过输入00:15, 04:30实现多时间设置,但编写的PowerShell脚本仅首个时间00:15生效,无报错,脚本中使用了New-ItemProperty而非Set-ItemProperty,询问仅首个时间生效的原因及解决方法。
原脚本:
Import-Module WebAdministration $RecycleTimes = @("00:15", "04:30") $PrivateMemory = 1468006 $sites = Get-ChildItem 'IIS:\AppPools\' <# | Where-Object { $_.recycling.periodicRestart.schedule.TotalMilliseconds -gt 1 } #> foreach ($s in $sites) { # 关闭固定间隔回收设置 Set-ItemProperty $s.PSPath -Name Recycling.periodicRestart.time -Value 0.00:00:00 # 设置应用池回收时间 Clear-ItemProperty $s.PSPath -Name Recycling.periodicRestart.schedule foreach ($RecycleTime in $RecycleTimes) { New-ItemProperty $s.PSPath -Name Recycling.periodicRestart.schedule -Value @{value=$RecycleTime} } # 设置私有内存限制 Set-ItemProperty $s.PSPath -Name recycling.periodicrestart.privateMemory -Value $PrivateMemory }
原因分析
Recycling.periodicRestart.schedule本质是ScheduleElementCollection类型的集合对象,你用New-ItemProperty循环添加时间时,每次调用都会重新创建整个schedule属性并覆盖之前的设置——第二次调用时会把第一次添加的00:15替换成04:30,最终只保留最后一次设置的值,而非向集合中追加元素。
解决方法
有两种可靠方式实现多回收时间设置:
方法1:直接操作集合对象(推荐)
直接调用集合的Add()方法添加时间条目,避免属性覆盖:
Import-Module WebAdministration $RecycleTimes = @("00:15", "04:30") $PrivateMemory = 1468006 $appPools = Get-ChildItem 'IIS:\AppPools\' foreach ($pool in $appPools) { # 关闭固定间隔回收 $pool.recycling.periodicRestart.time = [TimeSpan]::Zero $pool | Set-Item # 清空现有回收计划 $pool.recycling.periodicRestart.schedule.Clear() # 逐个添加回收时间 foreach ($time in $RecycleTimes) { $schedule = New-Object Microsoft.Web.Administration.ScheduleElement $schedule.Value = [TimeSpan]$time $pool.recycling.periodicRestart.schedule.Add($schedule) } # 设置私有内存限制 $pool.recycling.periodicRestart.privateMemory = $PrivateMemory # 保存更改 $pool | Set-Item }
方法2:一次性传递多值给Set-ItemProperty
直接将时间数组传递给Set-ItemProperty,一次性完成多时间设置:
Import-Module WebAdministration $RecycleTimes = @("00:15", "04:30") $PrivateMemory = 1468006 $appPools = Get-ChildItem 'IIS:\AppPools\' foreach ($pool in $appPools) { # 关闭固定间隔回收 Set-ItemProperty $pool.PSPath -Name Recycling.periodicRestart.time -Value 0.00:00:00 # 清空现有计划后,一次性设置多个回收时间 Clear-ItemProperty $pool.PSPath -Name Recycling.periodicRestart.schedule Set-ItemProperty $pool.PSPath -Name Recycling.periodicRestart.schedule -Value $RecycleTimes # 设置私有内存限制 Set-ItemProperty $pool.PSPath -Name recycling.periodicrestart.privateMemory -Value $PrivateMemory }
内容的提问来源于stack exchange,提问作者user20948243
相关产品推荐
相关产品推荐

