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() }
|