PowerShell 技能连载 - Kubernetes 节点智能编排

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
function Invoke-K8sNodeOrchestration {
[CmdletBinding()]
param(
[ValidateSet('ScaleUp','ScaleDown','Maintenance')]
[string]$Operation,
[int]$NodeCount = 1
)

$nodePool = Get-AzAksNodePool -ClusterName 'prod-cluster'
$metrics = Invoke-RestMethod -Uri 'http://k8s-metrics:8080/api/v1/nodes'

switch ($Operation) {
'ScaleUp' {
$newCount = $nodePool.Count + $NodeCount
Update-AzAksNodePool -Name $nodePool.Name -Count $newCount
Write-Host "节点池已扩容至$newCount个节点"
}
'ScaleDown' {
$nodesToRemove = $metrics.Nodes |
Where-Object { $_.CpuUsage -lt 20 } |
Select-Object -First $NodeCount
$nodesToRemove | ForEach-Object {
Set-AzAksNode -Name $_.Name -State Draining
}
}
'Maintenance' {
$metrics.Nodes | Where-Object { $_.HealthStatus -ne 'Healthy' } |
ForEach-Object {
Add-K8sNodeLabel -Node $_.Name -Label @{
'maintenance' = (Get-Date).ToString('yyyyMMdd')
}
}
}
}
}

核心功能

  1. 节点自动扩缩容策略
  2. 基于资源利用率的智能调度
  3. 维护模式自动标签管理
  4. 与Azure AKS深度集成

典型应用场景

  • 应对突发流量自动扩容节点
  • 低负载时段自动缩容节约成本
  • 异常节点自动隔离维护
  • 跨可用区节点平衡管理

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

[ValidateSet('Classification','Anomaly')]
[string]$AnalysisType = 'Classification'
)

$analysisReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
TotalEntries = 0
DetectedPatterns = @()
ModelAccuracy = 0
}

try {
# 加载预训练机器学习模型
$model = Import-MLModel -Path "$PSScriptRoot/log_analysis_model.zip"

# 预处理日志数据
$logData = Get-Content $LogPath |
ConvertFrom-LogEntry -ErrorAction Stop |
Select-Object TimeGenerated, Message, Level

$analysisReport.TotalEntries = $logData.Count

# 执行AI分析
$predictions = switch($AnalysisType) {
'Classification' {
$logData | Invoke-MLClassification -Model $model
}
'Anomaly' {
$logData | Invoke-MLAnomalyDetection -Model $model
}
}

# 生成检测报告
$analysisReport.DetectedPatterns = $predictions |
Where-Object { $_.Probability -gt 0.7 } |
Select-Object LogMessage, PatternType, Probability

# 计算模型准确率
$analysisReport.ModelAccuracy = ($predictions.ValidationScore | Measure-Object -Average).Average
}
catch {
Write-Error "日志分析失败: $_"
}

# 生成智能分析报告
$analysisReport | Export-Csv -Path "$env:TEMP/AILogReport_$(Get-Date -Format yyyyMMdd).csv"
return $analysisReport
}

核心功能

  1. 机器学习模型集成调用
  2. 日志数据智能分类与异常检测
  3. 预测结果概率分析
  4. 模型准确率动态计算

应用场景

  • IT运维日志模式识别
  • 安全事件自动化检测
  • 系统故障预测分析
  • 日志数据质量评估

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实践中的资源优化
  • 预算执行情况跟踪
  • 云服务商比价数据支持

PowerShell 技能连载 - Azure AD安全审计自动化

在云身份管理日益重要的今天,定期安全审计成为保障企业数字资产的关键。本文演示如何通过PowerShell自动执行Azure AD安全配置检测,实现实时安全态势监控。

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 Invoke-AzureADSecurityAudit {
param(
[string]$TenantId,
[switch]$ExportReport
)

try {
# 连接Azure AD
Connect-AzureAD -TenantId $TenantId | Out-Null

# 安全基线检测
$results = @(
[PSCustomObject]@{
CheckItem = '多重认证状态'
Result = (Get-AzureADMSAuthorizationPolicy).DefaultUserRolePermissions.AllowedToCreateApps
},
[PSCustomObject]@{
CheckItem = '旧协议支持状态'
Result = (Get-AzureADDirectorySetting | Where-Object {$_.DisplayName -eq 'OrganizationProperties'}).Values
}
)

# 生成报告
if ($ExportReport) {
$results | Export-Csv -Path "./SecurityAudit_$(Get-Date -Format yyyyMMdd).csv" -NoTypeInformation
}

return $results
}
catch {
Write-Error "审计失败:$_"
}
finally {
Disconnect-AzureAD
}
}

实现原理分析:

  1. 通过AzureAD模块实现与云身份服务的认证连接
  2. 检测关键安全配置项包括MFA实施状态和旧版协议支持情况
  3. 支持CSV报告导出功能便于存档分析
  4. 自动清理会话确保操作安全性
  5. 结构化返回结果便于后续处理

该脚本将原本需要人工操作的审计流程自动化,特别适合需要持续合规监控的金融和医疗行业应用场景。

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

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 技能连载 - 容器化脚本自动化管理

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
function Invoke-ContainerPipeline {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$ImageName,
[string]$DockerfilePath = './Dockerfile'
)

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

# 构建Docker镜像
$buildOutput = docker build -t $ImageName -f $DockerfilePath . 2>&1
$report.BuildLog += $buildOutput

# 推送镜像到仓库
if ($LASTEXITCODE -eq 0) {
$pushOutput = docker push $ImageName 2>&1
$report.BuildLog += $pushOutput
}

# 部署到Kubernetes
if ($LASTEXITCODE -eq 0) {
$k8sOutput = kubectl apply -f deployment.yaml 2>&1
$report.DeploymentStatus += [PSCustomObject]@{
Cluster = (kubectl config current-context)
Status = if($LASTEXITCODE -eq 0){'Success'}else{'Failed'}
Output = $k8sOutput
}
}

# 生成HTML报告
$htmlReport = $report | ConvertTo-Html -Fragment
$htmlReport | Out-File "$env:TEMP/ContainerReport_$(Get-Date -Format yyyyMMdd).html"
return $report
}

核心功能

  1. Docker镜像自动化构建
  2. 容器仓库自动推送
  3. Kubernetes部署集成
  4. HTML运维报告生成

典型应用场景

  • 持续集成/持续部署(CI/CD)
  • 跨环境容器镜像管理
  • 蓝绿部署策略实施
  • 容器化应用生命周期管理

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
function Invoke-AIOpsAssistant {
param(
[Parameter(Mandatory=$true)]
[string]$Prompt,
[int]$MaxTokens = 200
)

$apiKey = 'sk-xxxxxxxxxxxx'
$headers = @{
'Authorization' = "Bearer $apiKey"
'Content-Type' = 'application/json'
}

$body = @{
model = 'gpt-3.5-turbo'
messages = @(
@{
role = 'system'
content = '你是一个PowerShell专家,根据用户需求生成可直接运行的脚本。要求:1) 使用原生命令 2) 添加详细注释 3) 包含错误处理'
},
@{
role = 'user'
content = $Prompt
}
)
max_tokens = $MaxTokens
} | ConvertTo-Json -Depth 5

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

$generatedCode = $response.choices[0].message.content
$tempScript = [System.IO.Path]::GetTempFileName() + '.ps1'
$generatedCode | Out-File -FilePath $tempScript
& $tempScript
}
catch {
Write-Error "AI脚本生成失败:$_"
}
}

核心功能:

  1. 集成OpenAI ChatGPT API实现自然语言转PowerShell脚本
  2. 自动生成带错误处理和注释的生产级代码
  3. 安全执行临时脚本文件
  4. 支持自定义提示工程参数

应用场景:

  • 快速生成AD用户批量管理脚本
  • 自动创建资源监控报表
  • 生成复杂日志分析管道命令

PowerShell 技能连载 - Windows系统自动化优化

在企业IT运维中,系统服务的合理配置直接影响服务器性能。传统手动优化方式效率低下,本文演示如何通过PowerShell实现Windows服务的自动化管控与系统性能调优。

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
function Optimize-WindowsSystem {
param(
[ValidateRange(1,24)]
[int]$IdleThresholdHours = 4,
[switch]$CleanTempFiles
)

try {
# 检测闲置服务
$idleServices = Get-Service | Where-Object {
$_.Status -eq 'Running' -and
(Get-Process -Name $_.Name -ErrorAction SilentlyContinue).StartTime -lt (Get-Date).AddHours(-$IdleThresholdHours)
}

# 关闭非核心闲置服务
$idleServices | Where-Object {$_.DisplayName -notmatch 'Critical'} | Stop-Service -Force

# 清理临时文件
if ($CleanTempFiles) {
$tempPaths = @('$env:TEMP','$env:SystemRoot\Temp','$env:SystemRoot\Prefetch')
Remove-Item -Path $tempPaths -Recurse -Force -ErrorAction SilentlyContinue
}

# 生成优化报告
[PSCustomObject]@{
StoppedServices = $idleServices.Count
TempFilesCleaned = if($CleanTempFiles){ (Get-ChildItem $tempPaths -Recurse | Measure-Object).Count }else{ 0 }
Timestamp = Get-Date
} | Export-Clixml -Path "$env:ProgramData\SystemOptimizationReport.xml"
}
catch {
Write-EventLog -LogName Application -Source 'SystemOptimizer' -EntryType Error -EventId 501 -Message $_.Exception.Message
}
}

实现原理分析:

  1. 通过进程启动时间判断服务闲置状态,避免误停关键服务
  2. 支持临时文件清理功能并配备安全删除机制
  3. 采用XML格式记录优化操作审计日志
  4. 集成Windows事件日志实现错误追踪
  5. 参数验证机制防止误输入数值

该脚本将系统维护工作从手动操作转为计划任务驱动,特别适合需要批量管理数据中心服务器的运维场景。

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 技能连载 - OpenAI 智能运维自动化

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

[ValidateRange(1,100)]
[int]$MaxTokens = 60
)

$apiKey = $env:OPENAI_API_KEY
$prompt = @"
作为资深PowerShell运维专家,请根据以下运维场景生成可执行的解决方案:
场景:$OperationContext
要求:
1. 使用标准PowerShell命令
2. 包含错误处理机制
3. 输出结构化数据
4. 确保跨平台兼容性
"@

$body = @{
model = "gpt-3.5-turbo"
messages = @(@{role="user"; content=$prompt})
max_tokens = $MaxTokens
} | ConvertTo-Json

$response = Invoke-RestMethod -Uri 'https://api.openai.com/v1/chat/completions' \
-Method Post \
-Headers @{ Authorization = "Bearer $apiKey" } \
-ContentType 'application/json' \
-Body $body

$codeBlock = $response.choices[0].message.content -replace '```powershell','' -replace '```',''
[scriptblock]::Create($codeBlock).Invoke()
}

核心功能

  1. 自然语言转PowerShell代码生成
  2. 动态脚本编译与执行
  3. OpenAI API安全集成
  4. 跨平台兼容性保障

典型应用场景

  • 根据自然语言描述自动生成日志分析脚本
  • 将故障现象描述转换为诊断代码
  • 创建复杂运维任务的快速原型
  • 生成符合企业规范的脚本模板