关于 windows-server
面向生产工作负载的 Windows Server 管理技能,适用于执行服务器配置和自动化的管理员。涵盖 IIS、Active Directory、PowerShell、事件日志及更新管理。
主要功能
- 01使用 PowerShell 管理服务器
- 02配置 IIS 网站与应用程序池
- 03管理 Active Directory 用户和组
- 04检查 Windows 事件日志
- 05管理 Windows 更新和计划任务
适用场景
- 01配置 Windows Server 2019/2022
- 02部署 IIS 网站和应用程序池
- 03维护域服务、用户与组策略
- 04排查事件日志或更新问题
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ bagelhole/ devops-security-agent-skills --skill windows-server安装后在 Claude Code 中输入/windows-server确认已加载。
详细介绍
Windows Server 管理
面向生产工作负载的 Windows Server 管理与 PowerShell 自动化,包括 IIS Web 托管、Active Directory 域服务和系统维护。
适用场景
- 预配或配置 Windows Server 2019/2022 实例
- 设置 IIS 网站、应用程序池和绑定
- 管理 Active Directory 用户、组和组策略
- 使用 PowerShell 自动执行管理任务
- 查看 Windows 事件日志以排查问题
- 在服务器上应用和管理 Windows 更新
前提条件
- 目标服务器上的管理员帐户
- 已内置 PowerShell 5.1+ 或已安装 PowerShell 7+
- 已配置远程桌面或 WinRM 访问
- Windows Server 2019 或 2022(桌面体验或 Server Core)
PowerShell 管理基础
# Check PowerShell version
$PSVersionTable.PSVersion
# Get system information
Get-ComputerInfo | Select-Object CsName, OsName, OsVersion, OsArchitecture
# List running processes sorted by CPU
Get-Process | Sort-Object CPU -Descending | Select-Object -First 20
# List all services and their status
Get-Service | Where-Object { $_.Status -eq 'Running' }
# Restart a service
Restart-Service -Name W3SVC -Force
# Get disk space on all drives
Get-PSDrive -PSProvider FileSystem | Select-Object Name, @{N='Used(GB)';E={[math]::Round($_.Used/1GB,2)}}, @{N='Free(GB)';E={[math]::Round($_.Free/1GB,2)}}
# Check uptime
(Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
# Open firewall port
New-NetFirewallRule -DisplayName "Allow HTTPS" -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow
# List firewall rules
Get-NetFirewallRule | Where-Object { $_.Enabled -eq 'True' -and $_.Direction -eq 'Inbound' } | Select-Object DisplayName, Action
# Set DNS client server addresses
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses ("10.0.0.2","10.0.0.3")
# PowerShell remoting to another server
Enter-PSSession -ComputerName server02 -Credential (Get-Credential)
# Run a command on multiple remote servers
Invoke-Command -ComputerName server01,server02,server03 -ScriptBlock { Get-Service W3SVC }
服务器角色和功能
# List all available roles and features
Get-WindowsFeature
# Install IIS with management tools
Install-WindowsFeature -Name Web-Server -IncludeManagementTools -IncludeAllSubFeature
# Install Active Directory Domain Services
Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
# Install DNS Server
Install-WindowsFeature -Name DNS -IncludeManagementTools
# Install DHCP Server
Install-WindowsFeature -Name DHCP -IncludeManagementTools
# Install File Server with deduplication
Install-WindowsFeature -Name FS-FileServer, FS-Data-Deduplication
# List installed features only
Get-WindowsFeature | Where-Object Installed | Select-Object Name, InstallState
# Remove a feature
Uninstall-WindowsFeature -Name Telnet-Client
IIS Web 服务器设置
# Import the IIS administration module
Import-Module WebAdministration
# Create a new application pool
New-WebAppPool -Name "ProductionPool"
Set-ItemProperty IIS:\AppPools\ProductionPool -Name processModel.identityType -Value 3 # NetworkService
Set-ItemProperty IIS:\AppPools\ProductionPool -Name managedRuntimeVersion -Value "" # No managed code (reverse proxy)
# Create a new website
New-Website -Name "MyApp" `
-Port 443 `
-Protocol https `
-PhysicalPath "C:\inetpub\myapp" `
-ApplicationPool "ProductionPool" `
-SslFlags 1
# Add an HTTP binding that redirects to HTTPS
New-WebBinding -Name "MyApp" -Protocol http -Port 80
# Bind an SSL certificate to the HTTPS site
$cert = Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.Subject -like "*example.com*" }
New-Item IIS:\SslBindings\0.0.0.0!443 -Value $cert
# Create a virtual directory
New-WebVirtualDirectory -Site "MyApp" -Name "static" -PhysicalPath "C:\inetpub\static"
# Start, stop, and restart a site
Start-Website -Name "MyApp"
Stop-Website -Name "MyApp"
Restart-WebAppPool -Name "ProductionPool"
# List all websites and their state
Get-Website | Select-Object Name, State, PhysicalPath, @{N='Bindings';E={$_.Bindings.Collection.bindingInformation}}
# Enable IIS logging with W3C format
Set-WebConfigurationProperty -PSPath "IIS:\Sites\MyApp" `
-Filter "system.webServer/httpLogging" `
-Name "dontLog" -Value $false
# URL Rewrite: redirect HTTP to HTTPS (requires URL Rewrite module)
# web.config rule:
@'
<rule name="HTTP to HTTPS" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
'@
Active Directory 基础知识
# Promote server to a new domain controller in a new forest
Install-ADDSForest `
-DomainName "corp.example.com" `
-DomainNetBIOSName "CORP" `
-InstallDns:$true `
-SafeModeAdministratorPassword (ConvertTo-SecureString "P@ssw0rd!" -AsPlainText -Force) `
-Force:$true
# Create an Organizational Unit
New-ADOrganizationalUnit -Name "Engineering" -Path "DC=corp,DC=example,DC=com"
# Create a new AD user
New-ADUser -Name "Jane Smith" `
-SamAccountName "jsmith" `
-UserPrincipalName "[email protected]" `
-Path "OU=Engineering,DC=corp,DC=example,DC=com" `
-AccountPassword (ConvertTo-SecureString "TempP@ss1" -AsPlainText -Force) `
-Enabled $true `
-ChangePasswordAtLogon $true
# Add user to a group
Add-ADGroupMember -Identity "Domain Admins" -Members "jsmith"
# Search for users in an OU
Get-ADUser -Filter * -SearchBase "OU=Engineering,DC=corp,DC=example,DC=com" | Select-Object Name, SamAccountName, Enabled
# Disable a user account
Disable-ADAccount -Identity "jsmith"
# Unlock a locked-out account
Unlock-ADAccount -Identity "jsmith"
# Reset a user password
Set-ADAccountPassword -Identity "jsmith" -Reset -NewPassword (ConvertTo-SecureString "NewP@ss1" -AsPlainText -Force)
# List all domain controllers
Get-ADDomainController -Filter * | Select-Object Name, IPv4Address, Site
# Check AD replication status
Get-ADReplicationPartnerMetadata -Target "dc01.corp.example.com"
repadmin /replsummary
Windows 更新管理
# Install the PSWindowsUpdate module (from PowerShell Gallery)
Install-Module -Name PSWindowsUpdate -Force
# Check for available updates
Get-WindowsUpdate
# Install all available updates (auto-reboot if needed)
Install-WindowsUpdate -AcceptAll -AutoReboot
# Install only critical and security updates
Install-WindowsUpdate -Category "Security Updates","Critical Updates" -AcceptAll
# View update history
Get-WUHistory | Select-Object -First 20 Title, Date, Result
# Schedule monthly patching via Task Scheduler
$action = New-ScheduledTaskAction -Execute "powershell.exe" `
-Argument "-NoProfile -Command Install-WindowsUpdate -AcceptAll -AutoReboot"
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 2am
Register-ScheduledTask -TaskName "MonthlyPatching" -Action $action -Trigger $trigger -User "SYSTEM" -RunLevel Highest
# WSUS configuration via Group Policy (registry keys)
# HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate
# WUServer = http://wsus.corp.example.com:8530
# WUStatusServer = http://wsus.corp.example.com:8530
事件日志分析
# View the 50 most recent System log errors
Get-EventLog -LogName System -EntryType Error -Newest 50
# Search for specific event IDs (e.g., unexpected shutdowns = 6008)
Get-EventLog -LogName System -InstanceId 6008
# Use Get-WinEvent for advanced filtering (newer cmdlet)
Get-WinEvent -FilterHashtable @{
LogName = 'Application'
Level = 2 # Error
StartTime = (Get-Date).AddDays(-1)
} | Select-Object TimeCreated, Id, Message -First 20
# Search Security log for failed logons (Event ID 4625)
Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4625
} | Select-Object TimeCreated, @{N='Account';E={$_.Properties[5].Value}}, @{N='Source';E={$_.Properties[19].Value}} -First 30
# Export events to CSV for analysis
Get-WinEvent -FilterHashtable @{ LogName='System'; Level=1,2 } |
Export-Csv -Path C:\Logs\system-errors.csv -NoTypeInformation
# Clear old event log entries (use cautiously)
Clear-EventLog -LogName Application
# Set maximum log size
Limit-EventLog -LogName Application -MaximumSize 512MB -OverflowAction OverwriteAsNeeded
计划任务
# Create a scheduled task to run a script daily at 3 AM
$action = New-ScheduledTaskAction -Execute "powershell.exe" `
-Argument "-NoProfile -File C:\Scripts\daily-maintenance.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 3am
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd
Register-ScheduledTask -TaskName "DailyMaintenance" -Action $action -Trigger $trigger -Settings $settings -User "SYSTEM"
# List all scheduled tasks
Get-ScheduledTask | Where-Object { $_.State -ne 'Disabled' } | Select-Object TaskName, State, TaskPath
# Run a task immediately
Start-ScheduledTask -TaskName "DailyMaintenance"
# Disable and remove a task
Disable-ScheduledTask -TaskName "DailyMaintenance"
Unregister-ScheduledTask -TaskName "DailyMaintenance" -Confirm:$false
故障排查
| 症状 | 诊断命令 | 常见修复方法 |
|---|---|---|
| IIS 站点返回 503 | Get-WebAppPoolState | 重启应用程序池;检查事件日志以查找崩溃记录 |
| 服务器 CPU 使用率过高 | Get-Process | Sort CPU -Desc | 确定进程;检查是否存在失控的 w3wp 或服务 |
| 磁盘空间不足 | Get-PSDrive -PSProvider FileSystem | 清理临时文件、IIS 日志和 Windows 更新缓存 |
| AD 帐户被锁定 | Search-ADAccount -LockedOut | Unlock-ADAccount;在安全日志中查找锁定来源 |
| Windows 更新失败 | Get-WindowsUpdate -Verbose | 运行 sfc /scannow,重置更新组件 |
| 服务无法启动 | Get-EventLog -LogName System -Newest 20 | 检查依赖项、凭据和端口冲突 |
| RDP 连接被拒绝 | Get-ItemProperty 'HKLM:\System\...\Terminal Server' | 确保已启用 RDP,且防火墙允许端口 3389 |
| DNS 解析失败 | Resolve-DnsName example.com | 检查 DNS 服务器设置和转发器配置 |
相关技能
linux-administration-- 跨平台比较与混合管理ssh-configuration-- Windows OpenSSH Server 的 SSH 访问user-management-- Linux 用户/组管理的相关概念systemd-services-- Windows 服务和任务计划程序的 Linux 对应项performance-tuning-- 性能监控与优化模式
评论
支持 Markdown