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 和 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
37
38
39
40
41
42
# 配置 OpenAI API 密钥
$openAIKey = 'your-api-key'

function Get-AIScript {
param(
[string]$Prompt
)

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

$body = @{
model = 'gpt-4'
messages = @(
@{
role = 'system'
content = '你是一个 PowerShell 专家,请生成符合最佳实践的脚本。要求:1. 包含错误处理 2. 支持verbose输出 3. 包含帮助文档'
},
@{
role = 'user'
content = $Prompt
}
)
} | ConvertTo-Json

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

$response.choices[0].message.content
}

# 示例:生成 AD 用户创建脚本
$prompt = @"
创建 PowerShell 函数 New-ADUserWithValidation,要求:
1. 验证输入的邮箱格式
2. 检查用户名唯一性
3. 自动生成随机初始密码
4. 支持WhatIf参数
"@

Get-AIScript -Prompt $prompt

此脚本演示如何通过 OpenAI API 自动生成符合企业规范的 PowerShell 脚本。通过系统提示词确保生成的脚本包含错误处理、verbose 输出等必要元素。实际使用时可扩展以下功能:

  1. 添加 Azure Key Vault 集成管理 API 密钥
  2. 实现脚本静态分析
  3. 与 CI/CD 流水线集成进行自动测试