适用于 Windows Server 2016 及以上版本,需安装 IIS 管理工具
Internet Information Services(IIS)是 Windows 上最流行的 Web 服务器,广泛用于托管 ASP.NET 应用、静态网站和反向代理。IIS 管理器(GUI)虽然直观,但在管理多台服务器或执行批量操作时效率极低。PowerShell 的 WebAdministration 模块提供了完整的 IIS 管理能力,可以实现网站创建、应用池管理、绑定配置和性能调优的全面自动化。
本文将讲解 IIS 的 PowerShell 管理技巧,涵盖日常运维的各个场景。
IIS 管理环境准备 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Install-WindowsFeature -Name Web-Server , Web-Mgmt-Tools , Web-Scripting-Tools Import-Module WebAdministrationGet-Website | Select-Object Name, State, PhysicalPath, @ {N='绑定' ; E={($_ .bindings.Collection | ForEach-Object { $_ .protocol + '://' + $_ .bindingInformation }) -join ', ' }} | Format-Table -AutoSize Get-IISAppPool | Select-Object Name, State, @ {N='.NET版本' ; E={$_ .managedRuntimeVersion}}, @ {N='管线模式' ; E={$_ .managedPipelineMode}} | Format-Table -AutoSize
执行结果示例:
1 2 3 4 5 6 7 8 9 Name State PhysicalPath 绑定 ---- ----- ------------ ---- Default Started C:\inetpub\wwwroot http:// *:80 : MyApp Started D:\Apps\MyApp http:// *:8080 :, https:// *:443 : Name State .NET 版本 管线模式 ---- ----- -------- -------- DefaultAppPool Started v4.0 Integrated MyAppPool Started v4.0 Integrated
网站与应用池管理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 New-IISAppPool -Name "NewAppPool" -managedRuntimeVersion "v4.0" Set-ItemProperty IIS:\AppPools\NewAppPool -Name processModel.identityType -Value ApplicationPoolIdentitySet-ItemProperty IIS:\AppPools\NewAppPool -Name recycling.periodicRestart.time -Value "00:00:00" Write-Host "应用池已创建:NewAppPool" -ForegroundColor Green$siteParams = @ { Name = "MyNewSite" PhysicalPath = "D:\Apps\MyNewSite" Port = 8090 ApplicationPool = "NewAppPool" } New-IISSite @siteParamsWrite-Host "网站已创建:MyNewSite" -ForegroundColor Green$cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_ .Subject -match 'myapp.contoso.com' } | Select-Object -First 1 New-IISSiteBinding -Name "MyNewSite" -BindingInformation "*:443:myapp.contoso.com" ` -Protocol https -CertificateThumbPrint $cert .Thumbprint -CertStoreLocation "Cert:\LocalMachine\My" Start-Website -Name "MyNewSite" Stop-Website -Name "MyNewSite" Restart-WebAppPool -Name "NewAppPool" Remove-IISSite -Name "MyNewSite" -Confirm :$false Remove-IISAppPool -Name "NewAppPool" -Confirm :$false
执行结果示例:
1 2 应用池已创建:NewAppPool 网站已创建:MyNewSite
应用池健康监控 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 function Get-AppPoolHealthReport { $appPools = Get-IISAppPool $report = foreach ($pool in $appPools ) { $workerProcesses = Get-Process -Name w3wp -ErrorAction SilentlyContinue | Where-Object { $_ .AppPoolName -eq $pool .Name } $totalMemory = 0 $totalCPU = 0 $wpCount = 0 foreach ($wp in $workerProcesses ) { $totalMemory += $wp .WorkingSet64 $totalCPU += $wp .CPU $wpCount ++ } [PSCustomObject ]@ { 名称 = $pool .Name 状态 = $pool .State 工作进程 = $wpCount 内存MB = [math ]::Round($totalMemory / 1 MB, 2 ) 运行时 = $pool .managedRuntimeVersion 身份 = $pool .processModel.identityType 上次回收 = (Get-ItemProperty "IIS:\AppPools\$ ($pool .Name)" -Name recycling.logEventOnRecycle -ErrorAction SilentlyContinue).Value } } $report | Format-Table -AutoSize } Get-AppPoolHealthReport
执行结果示例:
1 2 3 4 ---- ---- -------- ------ ------ ---- . . . .
IIS 配置导出与迁移 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 function Export-IISConfig { param ([string ]$OutputPath = "C:\Config\IIS-Backup" ) New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null Get-IISAppPool | Export-Clixml -Path "$OutputPath \AppPools.xml" Get-Website | Export-Clixml -Path "$OutputPath \Websites.xml" Copy-Item "$env:windir \System32\inetsrv\config\applicationHost.config" ` "$OutputPath \applicationHost.config.bak" Write-Host "IIS 配置已导出到:$OutputPath " -ForegroundColor Green } function Get-IISLogSummary { param ( [string ]$SiteName = "Default Web Site" , [int ]$TopUrls = 10 ) $logPath = (Get-Website -Name $SiteName ).logfile.directory $logPath = $logPath -replace '%SystemDrive%' , $env:SystemDrive $latestLog = Get-ChildItem $logPath -Filter "*.log" -Recurse | Sort-Object LastWriteTime -Descending | Select-Object -First 1 Write-Host "分析日志:$ ($latestLog .FullName)" -ForegroundColor Cyan $header = Get-Content $latestLog .FullName | Where-Object { $_ -match '^#Fields:' } | Select-Object -First 1 $fields = ($header -replace '^#Fields:\s*' , '' ) -split '\s+' $entries = Get-Content $latestLog .FullName -Tail 10000 | Where-Object { $_ -notmatch '^#' -and $_ .Trim() } | ConvertFrom-Csv -Delimiter ' ' -Header $fields $entries | Group-Object 'cs-uri-stem' | Sort-Object Count -Descending | Select-Object -First $TopUrls Count, Name | Format-Table -AutoSize } Get-IISLogSummary -SiteName "MyApp" -TopUrls 10
执行结果示例:
1 2 3 4 5 6 7 8 9 10 IIS 配置已导出到:C:\Config\IIS-Backup 分析日志:C:\inetpub\logs\LogFiles\W3SVC2\ex250611.log Count Name ----- ---- 2345 /api/users 1876 /api/products 987 /static/css/main.css 654 /api/orders
注意事项
应用池回收 :配置合理的回收间隔。默认 29 小时回收一次可能导致请求中断,建议在低峰期回收
权限配置 :应用池的 Identity 账户需要对网站目录有读取权限
HTTPS 证书 :使用 Let’s Encrypt 或组织内部 CA 证书时,确保证书自动续期机制正常
日志管理 :IIS 日志增长很快,配置日志轮转和定期归档清理
Web.config 继承 :子目录的 web.config 会继承父目录的配置,可能导致冲突。使用 <location> 标签控制继承范围
32位应用 :如果应用需要 32 位模式,在应用池中设置 enable32BitAppOnWin64 为 true