You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:修正PowerShell脚本以更新IIS缓存配置值

修正IIS客户端缓存配置的PowerShell脚本

我来帮你搞定这个问题!你当前的脚本没达到预期效果,主要是两个关键点没处理好:没指定目标站点(默认会修改全局配置,大概率不是你想要的),还有缓存模式和参数的搭配逻辑不对。下面是修正后的方案:

问题分析

  1. 未指定站点:原脚本没有-Location参数,会直接修改IIS的全局配置,如果你想给某个特定站点设置缓存,这就完全没命中目标。
  2. 参数不匹配:当cacheControlMode设为UseExpires时,cacheControlMaxAge参数是不生效的——因为UseExpires模式是优先遵循httpExpires的绝对过期时间,而cacheControlMaxAge是对应UseMaxAge模式的相对过期参数,两者不能混用。

修正后的脚本

针对特定站点配置(推荐)

把YourSiteName替换成你实际的站点名称,脚本会精准修改目标站点的缓存配置:

Import-Module WebAdministration

# 替换为你的目标站点名称
$targetSite = "YourSiteName"

# 配置UseExpires模式(使用绝对过期时间)
Set-WebConfigurationProperty -Filter "/system.webServer/staticContent/clientCache" `
    -Name cacheControlMode -Value "UseExpires" `
    -Location $targetSite

Set-WebConfigurationProperty -Filter "/system.webServer/staticContent/clientCache" `
    -Name httpExpires -Value "Tue, 20 Feb 2020 00:00:00 GMT" `
    -Location $targetSite

# 如果你想用相对过期时间(比如2小时),请切换为UseMaxAge模式,注释上面的代码,启用下面的代码:
# Set-WebConfigurationProperty -Filter "/system.webServer/staticContent/clientCache" `
#     -Name cacheControlMode -Value "UseMaxAge" `
#     -Location $targetSite
# 
# Set-WebConfigurationProperty -Filter "/system.webServer/staticContent/clientCache" `
#     -Name cacheControlMaxAge -Value "02:00:00" `
#     -Location $targetSite

# 重启站点让配置生效
Restart-WebSite -Name $targetSite

修改全局IIS配置(不推荐,会影响所有站点)

如果你确实需要修改全局配置,去掉-Location参数即可,但记得重启整个IIS服务:

Import-Module WebAdministration

Set-WebConfigurationProperty -Filter "/system.webServer/staticContent/clientCache" `
    -Name cacheControlMode -Value "UseExpires"

Set-WebConfigurationProperty -Filter "/system.webServer/staticContent/clientCache" `
    -Name httpExpires -Value "Tue, 20 Feb 2020 00:00:00 GMT"

# 重启IIS服务
Restart-Service W3SVC

验证配置是否生效

执行完脚本后,你可以用下面的命令检查配置是否正确应用:

# 检查特定站点的配置
Get-WebConfigurationProperty -Filter "/system.webServer/staticContent/clientCache" `
    -Name cacheControlMode,cacheControlMaxAge,httpExpires `
    -Location $targetSite

# 检查全局配置
Get-WebConfigurationProperty -Filter "/system.webServer/staticContent/clientCache" `
    -Name cacheControlMode,cacheControlMaxAge,httpExpires

内容的提问来源于stack exchange,提问作者 Prasanth K S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:32:29