Help from ChatGPT on Powershell coding from console

Hi,

I thought that some of you might find this helpful, so I am sharing a simple script which connect to ChatGPT to get simple answers on Powershell related issues directly in the console.

To run the script you need API key which can be obtained from OpenAI after registration. You will get 18$ credit for first 3 months. After the trial period you will need to buy the service. The API key need to be stored in a file in a secure way (read the script to find a command how to create this file)

Feel free to improve the script as you wish.

# Help on Powershell coding from the console
# Author: Mariusz Gadula
# April 1, 2023

# Store the API key in the same folder as the script with this command
# read-host -assecurestring | convertfrom-securestring | out-file .\SecureApiKey.txt

# Read your OpenAI API key
$secureApiKey = get-content .\SecureApiKey.txt | convertto-securestring

# Convert SecureString to plain text
$apiKey =  (New-Object System.Net.NetworkCredential("",$secureApiKey)).Password

# Set the endpoint for the API
$endpoint = "https://api.openai.com/v1/chat/completions"

$messages = @(
    @{
        role = "system"
        content = "You are Powershell developer. You reply with brief, to-the-point answers with no elaboration."
    }
)

# Build the request object with the prompt as the first message
$request = @{
    model="gpt-3.5-turbo"
    max_tokens = 1024
    temperature = 0.7
    messages = $messages
}

# Loop until the user enters "exit"
while ($prompt -ne "exit") {
    # Prompt the user for input
    Write-Host -ForegroundColor Green "You:"
    $prompt = Read-Host

    # Add the user's message to the request object
    $request.messages += @{
        role = "user"
        content = $prompt
    }

    # Build the JSON request
    $json = $request | ConvertTo-Json

    # Send the request to the API
    $response = Invoke-RestMethod -Uri $endpoint -Method POST -Headers @{
        Authorization = "Bearer $apiKey"
        "Content-Type" = "application/json"
    } -Body $json

    # Get the response text
    $text = $response.choices[0].message.content 


    # Add the bot's message to the request object
    $request.messages += @{
	role = "assistant"
        content = $text
    }

    # Print the response
    Write-Host  -ForegroundColor Yellow "ChatGPT:"
    Write-Host "$text`n"

}

Example:

1 Like