PowerShell 技能连载 - Desired State Configuration

适用于 PowerShell 5.1 及以上版本(Windows),PowerShell 7 需安装 PSDesiredStateConfiguration 模块

在运维领域,”配置漂移”是一个永恒的痛点——服务器的实际状态随时间推移逐渐偏离预期配置,导致难以排查的故障和安全隐患。微软的 Desired State Configuration(DSC)正是为解决这个问题而设计的声明式配置管理框架。与 Ansible、Chef、Puppet 类似,DSC 让你用代码定义服务器”应该是什么样”,然后由系统自动确保配置一致。

本文将介绍 DSC 的核心概念、如何编写配置脚本、推拉两种工作模式,以及在 PowerShell 7 中使用 DSC 的注意事项。

阅读更多

PowerShell 技能连载 - 系统性能监控实战

适用于 PowerShell 7.0 及以上版本

在服务器运维和 DevOps 实践中,系统性能监控是保障业务稳定运行的基石。无论是排查突发的性能抖动,还是进行容量规划和趋势分析,都需要一套可靠的监控手段。传统的 GUI 工具(如任务管理器、perfmon)虽然直观,但不适合自动化场景和大规模服务器管理。

PowerShell 提供了对 WMI/CIM 类、.NET 性能计数器和系统 API 的完整访问能力,让我们可以用脚本化的方式采集、分析和导出系统性能数据。本文将介绍如何使用 PowerShell 构建一套实用的系统性能监控方案,涵盖 CPU、内存、磁盘、进程、网络等关键指标。

阅读更多

PowerShell 技能连载 - CI/CD 流水线中的 PowerShell 实践

适用于 PowerShell 7.0 及以上版本,需要 GitHub 账号

2025 年,CI/CD(持续集成/持续部署)已经成为软件交付的标准流程。无论是小型个人项目还是企业级微服务架构,自动化构建、测试和部署的能力都直接影响着交付效率和代码质量。GitHub Actions 作为目前最流行的 CI/CD 平台之一,原生支持 PowerShell 运行环境,这让 PowerShell 用户可以无缝融入 DevOps 工作流。

PowerShell 在 CI/CD 场景中有独特优势:强大的对象管道让数据处理变得简洁,跨平台支持(PowerShell 7+)让同一套脚本可以在 Windows、Linux 和 macOS Runner 上运行,丰富的模块生态则覆盖了从代码质量检查到部署验证的各个环节。本文将从脚本设计原则出发,逐步构建一个完整的 CI/CD 流水线方案。

阅读更多

PowerShell 技能连载 - Git 版本控制集成

适用于 PowerShell 7.0 及以上版本,需要安装 git

2025 年,几乎所有开发者都在使用 Git 进行版本管理。PowerShell 脚本作为基础设施即代码(IaC)的核心组成部分,同样需要纳入版本控制。将 Git 操作集成到 PowerShell 工作流中,不仅可以追踪脚本变更历史,还能实现自动化部署、配置审计和团队协作。

虽然 Git 自带命令行工具,但直接在 PowerShell 中调用 git 命令有时不太方便——输出格式不友好、错误处理不够优雅、与其他 PowerShell 对象的互操作性差。本文将展示如何在 PowerShell 中优雅地调用 Git、封装常用操作、构建自动化工作流。

阅读更多

PowerShell 技能连载 - JSON 与 YAML 配置管理

适用于 PowerShell 7.0 及以上版本

在 DevOps 和基础设施即代码的实践中,配置文件管理是核心能力。无论是应用部署、容器编排还是 CI/CD 流水线,JSON 和 YAML 格式的配置文件无处不在。PowerShell 原生支持 JSON 的读写与转换,配合 powershell-yaml 模块也能轻松处理 YAML,包括 Kubernetes 风格的多文档格式。

本文将从实际场景出发,逐步介绍如何用 PowerShell 完成 JSON 配置读取与修改、YAML 解析、Schema 验证、模板渲染以及环境配置切换。

阅读更多

PowerShell 技能连载 - Docker 容器管理

适用于 Docker 20.10+ 及 PowerShell 7.0+

容器化部署已经从尝鲜走向了主流。无论是微服务架构还是 CI/CD 流水线,Docker 几乎无处不在。然而,日常运维中频繁手动输入 docker rundocker logs 等命令不仅效率低下,而且容易出错。PowerShell 凭借其强大的对象管道和函数封装能力,非常适合用来编排 Docker 操作——把重复性工作交给脚本,让运维人员专注于真正重要的事情。

本文将从环境检查、容器生命周期管理、批量巡检、镜像清理、日志收集五个方面,逐步展示如何用 PowerShell 高效管理 Docker 容器,最后给出一个完整的 Nginx 部署实战示例。

阅读更多

PowerShell 技能连载 - Terraform 多云环境集成与自动化

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
54
55
function Invoke-TerraformMultiCloud {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Azure','AWS','GCP')]
[string[]]$CloudProviders,

[string]$TfWorkingDir = '$PSScriptRoot/terraform'
)

$stateReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
DeploymentStatus = @{}
ResourceCounts = @{}
CrossCloudDependencies = @()
}

try {
# 初始化多供应商terraform工作区
$CloudProviders | ForEach-Object {
if ($PSCmdlet.ShouldProcess("Initialize $_ provider")) {
terraform -chdir=$TfWorkingDir init -backend-config="$_backend.hcl"
}
}

# 执行跨云资源编排
$planOutput = terraform -chdir=$TfWorkingDir plan -out=multicloud.tfplan
$stateReport.DeploymentStatus['Plan'] = $planOutput -match 'No changes' ? 'Stable' : 'Pending'

# 自动化应用配置
if ($planOutput -match 'to add') {
$applyOutput = terraform -chdir=$TfWorkingDir apply -auto-approve multicloud.tfplan
$stateReport.DeploymentStatus['Apply'] = $applyOutput -match 'Apply complete' ? 'Success' : 'Failed'
}

# 获取跨云资源状态
$tfState = terraform -chdir=$TfWorkingDir show -json | ConvertFrom-Json
$stateReport.ResourceCounts = $tfState.resources |
Group-Object provider_name |
ForEach-Object {@{$_.Name = $_.Count}}

# 分析云间依赖关系
$stateReport.CrossCloudDependencies = $tfState.resources |
Where-Object { $_.depends_on -match 'aws_|azurerm_' } |
Select-Object type, provider
}
catch {
Write-Error "多云部署失败: $_"
terraform -chdir=$TfWorkingDir destroy -auto-approve
}

# 生成基础设施即代码报告
$stateReport | Export-Csv -Path "$env:TEMP/MultiCloudReport_$(Get-Date -Format yyyyMMdd).csv"
return $stateReport
}

核心功能

  1. 多云供应商统一编排
  2. 基础设施配置自动化管理
  3. 跨云依赖关系可视化
  4. 部署状态实时跟踪

应用场景

  • 混合云资源统一管理
  • 跨云平台灾备方案实施
  • 多云成本优化分析
  • 基础设施合规检查

PowerShell 技能连载 - 自然语言生成运维脚本

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
function Invoke-AIScriptGeneration {
param(
[Parameter(Mandatory=$true)]
[string]$Prompt,
[ValidateSet('AWS','Azure','Windows','Linux')]
[string]$Environment = 'Windows'
)

$apiKey = $env:OPENAI_API_KEY
$headers = @{
'Authorization' = "Bearer $apiKey"
'Content-Type' = 'application/json'
}

$body = @{
model = 'gpt-4-turbo'
messages = @(
@{
role = 'system'
content = "你是一名资深PowerShell专家,根据用户需求生成可直接执行的运维脚本。当前环境:$Environment"
},
@{
role = 'user'
content = $Prompt
}
)
temperature = 0.3
max_tokens = 1024
} | ConvertTo-Json -Depth 5

try {
$response = Invoke-RestMethod -Uri 'https://api.openai.com/v1/chat/completions' \
-Method Post \
-Headers $headers \
-Body $body

$scriptBlock = [scriptblock]::Create($response.choices[0].message.content)
Write-Host "生成脚本验证通过:" -ForegroundColor Green
$scriptBlock.Invoke()
}
catch {
Write-Error "AI脚本生成失败: $($_.Exception.Message)"
}
}

核心功能:

  1. 集成OpenAI API实现自然语言转PowerShell脚本
  2. 支持多环境脚本生成(AWS/Azure/Windows/Linux)
  3. 自动脚本验证与安全执行机制
  4. 温度参数控制脚本生成稳定性

应用场景:

  • 新手运维人员快速生成标准脚本
  • 跨平台环境下的自动化模板生成
  • 复杂运维任务的快速原型开发
  • 企业知识库的脚本标准化沉淀

PowerShell 技能连载 - 混合云基础设施即代码实践

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
function Invoke-HybridIaC {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Azure','AWS','OnPrem')]
[string[]]$Environments,

[string]$DscConfigPath = '$PSScriptRoot/dsc'
)

$deploymentReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
AppliedConfigs = @()
ComplianceStatus = @{}
CrossPlatformIssues = @()
}

try {
# 应用Terraform基础设施
$Environments | ForEach-Object {
if ($PSCmdlet.ShouldProcess("Deploy $_ resources")) {
terraform -chdir="$DscConfigPath/terraform/$_" apply -auto-approve
}
}

# 执行DSC配置
$Environments | ForEach-Object {
$dscConfig = Get-ChildItem "$DscConfigPath/$_" -Filter *.ps1
$dscConfig | ForEach-Object {
$job = Start-Job -ScriptBlock {
param($config)
& $config.FullName
} -ArgumentList $_
$deploymentReport.AppliedConfigs += $job | Wait-Job | Receive-Job
}
}

# 验证混合云合规性
$deploymentReport.ComplianceStatus = $Environments | ForEach-Object {
$status = Test-DscConfiguration -CimSession (New-CimSession -ComputerName $_)
@{$_ = $status.InDesiredState ? 'Compliant' : 'Non-Compliant'}
}
}
catch {
Write-Error "混合云部署失败: $_"
terraform -chdir="$DscConfigPath/terraform" destroy -auto-approve
}

# 生成统一部署报告
$deploymentReport | Export-Clixml -Path "$env:TEMP/HybridIaC_Report_$(Get-Date -Format yyyyMMdd).xml"
return $deploymentReport
}

核心功能

  1. 多环境Terraform编排
  2. DSC配置跨平台应用
  3. 混合云合规性验证
  4. 原子化作业执行

应用场景

  • 混合云环境统一管理
  • 配置漂移自动修复
  • 跨云平台灾备部署
  • 基础设施合规审计

PowerShell与Terraform实现基础设施即代码

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
function Invoke-TerraformDeployment {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Environment
)

# 生成Terraform变量文件
$tfVars = @{
environment = $Environment
location = 'eastus'
vm_count = 3
} | ConvertTo-Json
$tfVars | Out-File -FilePath "./terraform.tfvars.json"

# 初始化并应用配置
terraform init -input=false
terraform apply -auto-approve -var-file="./terraform.tfvars.json"

# 获取输出变量
$output = terraform output -json | ConvertFrom-Json
[PSCustomObject]@{
PublicIP = $output.public_ip.value
StorageEndpoint = $output.storage_endpoint.value
}
}

# 执行多环境部署
'dev','staging','prod' | ForEach-Object {
Invoke-TerraformDeployment -Environment $_ -Verbose
}

核心功能:

  1. 自动化生成Terraform变量文件
  2. 集成Terraform CLI实现无人值守部署
  3. 解析基础设施输出参数

扩展方向:

  • 添加Azure Key Vault集成管理敏感信息
  • 实现漂移检测与自动修复
  • 与监控系统集成进行健康检查
PowerShell 技术 QQ 群