Let OpenAI improve and correct your PowerShell code

In this article, I will describe a simple way to let OpenAI improve and correct your PowerShell code. It will contain 2 main functions: Get-CodeImprovementSuggestion and Get-CodeFixSuggestion. Both accept a ScriptBlock parameter. As names indicate, the first one checks in OpenAI if there are some possible improvements. The second one checks for errors. Both are handy within your PowerShell console of choice. There will also be one helper function handling the API connection. Let’s start!

Register at OpenAI

As a first thing, you need an instance of OpenAI. For this purpose, you can register on the OpenAI website by clicking on the “Sign up” button. It’s the same process you follow for ChatGPT as the OpenAI API and ChatGPT are parts of the same suite. If you already have an OpenAI account, skip this chapter.

Once this is done, you will get a free credit for 5$ to use the OpenAI API. Let’s create a connection key (so you can authenticate from your script). Click on your user icon in the upper right corner of the website and open “View API keys”. There click on “Create new secret key”. Copy the newly generated key to a safe location. Once you close the pop-up window with it, you will lose the chance to read it again.


Now you need the helper function which sends prompts to AI. It accepts a single string parameter for the question. Remember to update the following code with the API key you got from the OpenAI page. For this example, I selected the chat completions endpoint. It works just good but of course you can experiment with other ones. I also used the GPT 3.5 Turbo model. It’s not the most intelligent one but it’s good enough while keeping the price significantly lower than GPT 4.

To avoid creativity and this way ensure an accurate reply, set the temperature to zero. You can also limit the max_tokens value. This way you can get shorter replies but save some tokens. Be careful with that. If you select too small number of max_tokens it can cut the reply somewhere in the middle of it.

In the end, this function returns the reply from the AI.

function Get-ChatGPTReply {
    param (
    $apiKey = "[PUT YOUR KEY HERE]"

    $endpoint = "https://api.openai.com/v1/chat/completions"

    $requestPayload = @{
        model = "gpt-3.5-turbo"
        messages = @(
                role = "user"
                content = $question
        temperature = 0
        max_tokens = 200
        top_p = 1
        frequency_penalty = 0
        presence_penalty = 0
    } | ConvertTo-Json

    $response = Invoke-RestMethod -Uri $endpoint -Headers @{
        "Authorization" = "Bearer $apiKey"
        "Content-Type" = "application/json"
    } -Method 'POST' -Body $requestPayload

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

Core functions

It’s time to create the core functions. Once you have the connectivity with the helper function, it’s quite easy to let OpenAI improve and correct your PowerShell code. Those 2 functions just accept a ScriptBlock and send it to the AI engine with a pre-defined question. It’s just a few lines of code for each function.

function Get-CodeImprovementSuggestion {
    param (
        [scriptblock] $code
    $message = "Please check if there could be any improvements in this powershell code: `n`n $code"
    Get-ChatGPTReply $message

function Get-CodeFixSuggestion {
    param (
        [scriptblock] $code
    $message = "This powershell code fails. Please provide a suggestion how to fix it: `n`n $code"
    Get-ChatGPTReply $message

That’s it! As simple as that.

Does it work?

Let’s make a short test to show how it works. I created a super simple script with possible improvements. It’s to show you that it really works, it’s able to find and suggest them.

How about the corrections? Let’s try with simple errors in the script. I made a typo in Get-Datee (double e) and missed a $ when referencing a variable. What’s the result? Both errors are quickly identified and corrections are found. I guess that I don’t need to explain how frustrating it is to find simple mistakes like these in long scripts… Of course, you can copy-paste the entire script into ChatGPT in your browser and ask for the same. But isn’t it handy to have such cmdlets ready for you in your PowerShell console?

Wiktor Mrówczyński

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top