PowerShell 技能连载 - AWS 自动化管理

适用于 PowerShell 5.1 及以上版本,需安装 AWS Tools for PowerShell

Amazon Web Services(AWS)是全球最大的公有云平台,拥有最丰富的云服务生态。AWS Tools for PowerShell 让 Windows 运维人员可以用熟悉的 PowerShell 语法管理 AWS 资源,无需切换到 Python 或 AWS CLI。从 EC2 实例管理到 S3 存储操作,从 IAM 权限控制到 CloudWatch 监控,所有 AWS 服务都可以通过 PowerShell 命令操作。

本文将讲解 AWS Tools 的安装配置、EC2 实例管理、S3 存储操作,以及常见的自动化场景。

阅读更多

PowerShell 技能连载 - Azure 自动化管理

适用于 PowerShell 7.0 及以上版本,需安装 Az PowerShell 模块

微软 Azure 是全球第二大公有云平台,而 PowerShell 是管理 Azure 资源的首选工具之一。Az PowerShell 模块提供了覆盖所有 Azure 服务的命令集,从虚拟机管理到存储操作,从网络配置到安全策略,都可以通过 PowerShell 脚本自动化完成。相比于 Azure Portal 的点击操作,PowerShell 脚本具有可重复、可版本控制、可审计的优势。

本文将讲解 Az 模块的基础使用、虚拟机管理、存储操作,以及常见自动化场景。

阅读更多

PowerShell 技能连载 - Azure多云成本优化实践

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
function Get-AzureCostAnalysis {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string[]]$SubscriptionIds,
[datetime]$StartDate = (Get-Date).AddDays(-30)
)

$report = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
ResourceAnalysis = @()
CostRecommendations = @()
}

foreach ($subId in $SubscriptionIds) {
Set-AzContext -SubscriptionId $subId | Out-Null

# 获取资源消耗数据
$resources = Get-AzResource | Where-Object {
$_.ResourceType -notin @('Microsoft.Resources/deployments','Microsoft.Resources/subscriptions')
}

$resourceGroups = $resources | Group-Object ResourceGroupName
foreach ($rg in $resourceGroups) {
$costData = Get-AzConsumptionUsageDetail -StartDate $StartDate -EndDate (Get-Date) -ResourceGroup $rg.Name

$report.ResourceAnalysis += [PSCustomObject]@{
Subscription = $subId
ResourceGroup = $rg.Name
TotalCost = ($costData | Measure-Object PretaxCost -Sum).Sum
UnderutilizedVMs = $rg.Group.Where{ $_.ResourceType -eq 'Microsoft.Compute/virtualMachines' }.Count
}
}
}

# 生成优化建议
$report.ResourceAnalysis | ForEach-Object {
if ($_.UnderutilizedVMs -gt 5) {
$report.CostRecommendations += [PSCustomObject]@{
Recommendation = "调整资源组 $($_.ResourceGroup) 中未充分利用的VM规模"
PotentialSavings = "预计节省 $([math]::Round($_.TotalCost * 0.3)) 美元"
}
}
}

$report | Export-Excel -Path "$env:TEMP/AzureCostReport_$(Get-Date -Format yyyyMMdd).xlsx"
return $report
}

核心功能

  1. 跨订阅资源消耗分析
  2. 闲置VM资源自动识别
  3. 成本节约潜力预测
  4. Excel报告自动生成

典型应用场景

  • 企业多云成本可视化管理
  • FinOps实践中的资源优化
  • 预算执行情况跟踪
  • 云服务商比价数据支持

多云环境成本优化自动化实践

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
function Get-CloudCostAnalysis {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Azure','AWS')]
[string]$CloudProvider
)

$threshold = 100 # 美元

switch ($CloudProvider) {
'Azure' {
$costData = Get-AzConsumptionUsageDetail -BillingPeriodName (Get-Date).ToString('yyyyMM') |
Group-Object ResourceGroup |
Select-Object Name,@{N='Cost';E={$_.Group.PretaxCost | Measure-Object -Sum | Select-Object -Expand Sum}}
}
'AWS' {
$costData = Get-CECostAndUsage -TimePeriod @{Start=(Get-Date).AddDays(-30).ToString('yyyy-MM-dd');End=(Get-Date).ToString('yyyy-MM-dd')} -Granularity MONTHLY |
Select-Object -Expand ResultsByTime |
Select-Object -Expand Groups |
Where-Object {$_.Metrics.UnblendedCost.Amount -gt $threshold}
}
}

$costData | Export-Csv -Path "${CloudProvider}_Cost_Report_$(Get-Date -Format yyyyMMdd).csv" -NoTypeInformation

if ($costData.Count -gt 5) {
Send-MailMessage -To 'finops@company.com' -Subject "[$CloudProvider] 成本异常警报" -Body "发现${threshold}美元以上资源:$($costData.Count)项"
}
}

核心功能:

  1. 支持Azure/AWS多云平台成本分析
  2. 自动识别异常支出资源
  3. 生成CSV报告并邮件告警
  4. 可配置成本阈值参数

扩展方向:

  • 集成Power BI可视化
  • 添加自动关闭闲置资源功能
  • 实现跨云平台成本对比分析

PowerShell 技能连载 - 边缘计算环境中的IoT设备监控

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 Get-IoTEdgeDeviceStatus {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$DeviceIPRange,

[ValidateRange(1,65535)]
[int]$PollingInterval = 300
)

$deviceReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
OnlineDevices = @()
OfflineDevices = @()
AbnormalMetrics = @()
}

# 执行Ping扫描发现设备
$discoveredDevices = Test-Connection -ComputerName $DeviceIPRange -Count 1 -AsJob |
Wait-Job | Receive-Job |
Where-Object { $_.StatusCode -eq 0 } |
Select-Object Address,ResponseTime

# 获取设备遥测数据
$discoveredDevices | ForEach-Object {
try {
$metrics = Invoke-RestMethod -Uri "http://$($_.Address)/metrics" -TimeoutSec 5

$deviceReport.OnlineDevices += [PSCustomObject]@{
IPAddress = $_.Address
Latency = $_.ResponseTime
CPUUsage = $metrics.cpu_usage
MemoryUsage = $metrics.memory_usage
}

if($metrics.cpu_usage -gt 90 -or $metrics.memory_usage -gt 85) {
$deviceReport.AbnormalMetrics += [PSCustomObject]@{
IPAddress = $_.Address
Metric = ($metrics | ConvertTo-Json)
Threshold = "CPU >90% 或 Memory >85%"
}
}
}
catch {
$deviceReport.OfflineDevices += $_.Address
}
}

# 生成HTML报告
$reportPath = "$env:TEMP/IoTEdgeReport_$(Get-Date -Format yyyyMMdd).html"
$deviceReport | ConvertTo-Html -Title "IoT设备健康报告" | Out-File $reportPath
return $deviceReport
}

核心功能

  1. 工业设备自动发现与状态采集
  2. 设备资源使用率实时监控
  3. 异常阈值自动预警
  4. HTML格式可视化报告

应用场景

  • 智能制造设备监控
  • 能源行业传感器网络
  • 智慧城市基础设施
  • 远程设备维护预警

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function Start-EdgeDeviceMonitor {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$BrokerUrl,

[Parameter(Mandatory=$true)]
[string[]]$DeviceTopics
)

Add-Type -Path "MQTTnet.dll"
$factory = [MQTTnet.MqttFactory]::new()
$client = $factory.CreateMqttClient()

$report = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
ConnectedDevices = @()
HealthStatus = @()
}

$clientOptions = [MQTTnet.Client.MqttClientOptionsBuilder]::new()
.WithTcpServer($BrokerUrl)
.Build()

$client.ConnectAsync($clientOptions).Wait()

$DeviceTopics | ForEach-Object {
$client.SubscribeAsync([MQTTnet.MqttTopicFilterBuilder]::new()
.WithTopic($_)
.Build()).Wait()

$client.ApplicationMessageReceivedHandler = [MQTTnet.MqttApplicationMessageReceivedHandler]{
param($e)
$payload = [System.Text.Encoding]::UTF8.GetString($e.ApplicationMessage.Payload)

$report.ConnectedDevices += [PSCustomObject]@{
DeviceID = $e.ApplicationMessage.Topic.Split('/')[-1]
LastSeen = Get-Date
Telemetry = $payload | ConvertFrom-Json
}

if ($payload -match '"status":"error"') {
$report.HealthStatus += [PSCustomObject]@{
DeviceID = $e.ApplicationMessage.Topic.Split('/')[-1]
ErrorCode = ($payload | ConvertFrom-Json).errorCode
Recommendation = "检查设备固件版本并重启服务"
}
}
}
}

Register-ObjectEvent -InputObject $client -EventName ApplicationMessageReceived -Action {
$global:report = $eventArgs | ForEach-Object { $_.UserEventArgs }
}

$report | Export-Csv -Path "$env:TEMP/EdgeDeviceReport_$(Get-Date -Format yyyyMMdd).csv"
return $report
}

核心功能

  1. MQTT协议设备状态实时订阅
  2. 边缘计算设备健康状态分析
  3. 异常事件自动化预警
  4. CSV报告持续输出

典型应用场景

  • 智能制造产线监控
  • 智慧城市基础设施管理
  • 农业物联网传感器网络
  • 能源设备远程诊断

PowerShell 技能连载 - 基于Azure Functions的无服务器安全检测

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-SecurityScan {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$ResourceGroup,

[ValidateSet('Critical','High','Medium')]
[string]$SeverityLevel = 'High'
)

$securityReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
ScannedResources = @()
SecurityFindings = @()
}

# 获取Azure安全中心警报
$alerts = Get-AzSecurityAlert -ResourceGroupName $ResourceGroup |
Where-Object { $_.Severity -eq $SeverityLevel }

# 自动化响应流程
$alerts | ForEach-Object {
$securityReport.ScannedResources += [PSCustomObject]@{
ResourceID = $_.ResourceId
AlertType = $_.AlertType
CompromiseEntity = $_.CompromisedEntity
}

# 触发自动化修复动作
if($_.AlertType -eq 'UnusualResourceDeployment') {
Start-AzResourceDelete -ResourceId $_.ResourceId -Force
$securityReport.SecurityFindings += [PSCustomObject]@{
Action = 'DeletedSuspiciousResource'
ResourceID = $_.ResourceId
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
}
}
}

# 生成安全态势报告
$securityReport | ConvertTo-Json -Depth 3 |
Out-File -FilePath "$env:TEMP/AzureSecReport_$(Get-Date -Format yyyyMMdd).json"
return $securityReport
}

核心功能

  1. 实时获取Azure安全中心高等级警报
  2. 异常资源部署自动隔离机制
  3. JSON格式安全态势报告生成
  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
53
54
55
56
57
58
59
60
61
62
63
64
65
function Get-CloudCostReport {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string[]]$SubscriptionIds,

[ValidateSet('Daily','Monthly')]
[string]$Granularity = 'Monthly'
)

$costReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
TotalCost = 0
ServiceBreakdown = @{}
OptimizationSuggestions = @()
}

try {
# 获取跨云成本数据
$costData = $SubscriptionIds | ForEach-Object {
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/$_/providers/Microsoft.CostManagement/query?api-version=2023-03-01" \
-Headers @{ Authorization = "Bearer $env:AZURE_TOKEN" } \
-Body (@{
type = "ActualCost"
timeframe = "MonthToDate"
dataset = @{
aggregation = @{
totalCost = @{
name = "Cost"
function = "Sum"
}
}
grouping = @(
@{
type = "Dimension"
name = "ServiceName"
}
)
}
} | ConvertTo-Json)
}

# 分析成本结构
$costReport.TotalCost = ($costData.properties.rows | Measure-Object -Property [0] -Sum).Sum
$costReport.ServiceBreakdown = $costData.properties.rows |
Group-Object { $_[1] } -AsHashTable |
ForEach-Object { @{$_.Key = [math]::Round($_.Value[0],2)} }

# 生成优化建议
$costData.properties.rows | Where-Object { $_[0] -gt 1000 } | ForEach-Object {
$costReport.OptimizationSuggestions += [PSCustomObject]@{
Service = $_[1]
Cost = $_[0]
Recommendation = "考虑预留实例或自动缩放配置"
}
}
}
catch {
Write-Error "成本数据获取失败: $_"
}

# 生成Excel格式报告
$costReport | Export-Excel -Path "$env:TEMP/CloudCostReport_$(Get-Date -Format yyyyMMdd).xlsx"
return $costReport
}

核心功能

  1. 跨云成本数据聚合分析
  2. 服务维度费用结构分解
  3. 智能优化建议生成
  4. Excel格式报告输出

应用场景

  • 多云环境成本监控
  • 预算超支预警
  • 资源使用效率优化
  • 财务部门合规报告

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

# 获取函数应用运行环境信息
$context = Get-AzContext
$functions = Get-AzFunctionApp -ResourceGroupName $ResourceGroup

$report = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
FunctionApps = @()
SecurityFindings = @()
}

# 检查TLS版本配置
$functions | ForEach-Object {
$config = Get-AzFunctionAppSetting -Name $_.Name -ResourceGroupName $ResourceGroup

$appReport = [PSCustomObject]@{
AppName = $_.Name
RuntimeVersion = $_.Config.NetFrameworkVersion
HTTPSOnly = $_.Config.HttpsOnly
MinTLSVersion = $config['minTlsVersion']
}
$report.FunctionApps += $appReport

if ($appReport.MinTLSVersion -lt '1.2') {
$report.SecurityFindings += [PSCustomObject]@{
Severity = 'High'
Description = "函数应用 $($_.Name) 使用不安全的TLS版本: $($appReport.MinTLSVersion)"
Recommendation = '在应用设置中将minTlsVersion更新为1.2'
}
}
}

# 生成安全报告
$report | Export-Clixml -Path "$env:TEMP/ServerlessSecurityReport_$(Get-Date -Format yyyyMMdd).xml"
return $report
}

核心功能

  1. Azure Functions运行环境自动检测
  2. TLS安全配置合规检查
  3. 零信任架构下的安全基线验证
  4. 自动化XML报告生成

典型应用场景

  • 无服务器架构安全审计
  • 云环境合规自动化核查
  • 持续安全监控(CSM)实现
  • DevOps流水线安全卡点集成
PowerShell 技术 QQ 群