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