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 Invoke-AIScriptGeneration { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$NaturalLanguageQuery, [ValidateRange(1,5)] [int]$MaxAttempts = 3 )
$codeReport = [PSCustomObject]@{ Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' GeneratedScript = $null ValidationErrors = @() OptimizationLevel = 0 }
try { $prompt = @" 作为PowerShell专家,请将以下运维需求转换为安全可靠的代码: 需求:$NaturalLanguageQuery 要求: 1. 包含try/catch错误处理 2. 支持WhatIf预执行模式 3. 输出结构化对象 4. 符合PowerShell最佳实践 "@
$response = Invoke-RestMethod -Uri 'https://api.openai.com/v1/chat/completions' \ -Headers @{ Authorization = "Bearer $env:OPENAI_API_KEY" } \ -Body (@{ model = "gpt-4-turbo" messages = @(@{ role = "user"; content = $prompt }) temperature = 0.2 max_tokens = 1500 } | ConvertTo-Json)
$validationResults = $response.choices[0].message.content | Where-Object { $_ -notmatch 'Remove-Item|Format-Table' } | Test-ScriptAnalyzer -Severity Error
$codeReport.GeneratedScript = $response.choices[0].message.content $codeReport.ValidationErrors = $validationResults $codeReport.OptimizationLevel = (100 - ($validationResults.Count * 20)) } catch { Write-Error "AI脚本生成失败: $_" if ($MaxAttempts -gt 1) { return Invoke-AIScriptGeneration -NaturalLanguageQuery $NaturalLanguageQuery -MaxAttempts ($MaxAttempts - 1) } }
$codeReport | Export-Csv -Path "$env:TEMP/AIScriptReport_$(Get-Date -Format yyyyMMdd).csv" -NoTypeInformation return $codeReport }
|