Use PowerShell to integrate OpenAI GPT with context menu

Do you know that it’s possible to use PowerShell to integrate OpenAI GPT with context menu in Windows? It’s even really simple and with help of this article everyone can make it. In this example, I’ll add a new item to context menu (when you right click on a file). It appears only for PowerShell files and allows you to use OpenAI to get summary of what a script does. You can adjust it to your needs. For example, to get a summary of a text file, explanation of file extension or whatever else you can imagine.

Prepare

If you don’t know how to start using OpenAI and more specifically how to do it with PowerShell, take a look here: Let OpenAI improve and correct your PowerShell code. In this article I describe step by step how to register at OpenAI and query the GPT engine directly from script. If you already have an account there, you are just ready to start, so please continue reading. Otherwise I encourage you to check the mentioned article firstly and then get back.

The script

As a baseline I used the same script as in the last article (link) with small adjustments. First one is the token limit. This time I set it to 2000 to cover description for scripts longer than few lines. By the way, be careful about the cost. In OpenAI you pay for tokens. To get a summary from a script, you need to post the script’s content to GPT engine which makes your query larger. For scripts with few hundred lines and above you can even exceed the limit on the AI side.

The second adjustment is to encrypt the API key. It’s much more convenient to store it somewhere than to provide each time. This of course requires to secure the key (keeping secrets in clean text is always a bad idea). You can use the most convenient way for you, I just used the Convert-ToSecureString (documentation: link) cmdlet, which risk is acceptable for my case.

I also created a new simple function to retrieve the script summary. It’s all put into a parametrized script, so I can call it in the easiest form. This is important because the context menu command is set directly in the registry – it’s really tricky to put complex PowerShell code there. Keeping it as simple as possible is the key to avoid unnecessary test & correct frustration.

The script accepts one argument which is the path of the file I want to check. Here it is:

param(
    $path
)

function Get-ChatGPTReply {
    param (
        [string]$question
    )
    $apiKeyS = "02234000d98c9fdd[...]4r1"
    $apiKey  = ([System.Management.Automation.PSCredential]::new("user",($apiKeyS | ConvertTo-SecureString))).GetNetworkCredential().Password

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

    $requestPayload = @{
        model = "gpt-3.5-turbo"
        messages = @(
            @{
                role = "user"
                content = $question
            }
        )
        temperature = 0
        max_tokens = 2000
        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
}

function Get-PowerShellScriptSummary {
    param (
        [string] $path
    )
    $message = "Provide short summary of actions made by the following PowerShell script: `n`n $(Get-Content $path)"
    Get-ChatGPTReply $message
}

Get-PowerShellScriptSummary "$path"
Read-Host

In the last line I just wait for pressing enter with the Read-Host cmdlet – the simplest way to avoid console window disappearing immediately after showing the answer.

I saved the script in C:\temp location with AI.ps1 name. It’s important because I will reference it in the registry.

Add context menu item

Open the registry editor (run regedit.exe). Go to Computer\HKEY_CLASSES_ROOT*\shell and create new key with a name meaningful for you. I set the default value to Ask OpenAI About it. This default value is the text visible inside the context menu. I also added a filter to show this item only for .ps1 files with the AppliesTo REG_SZ (value: .ps1).

Inside the new key, create another key named command (this name is important, you cannot change it). Set its default value to: powershell.exe -file c:\temp\AI.ps1 -path "%1" . It tells the File Explorer to run the script I created earlier and pass to it path of the right clicked file.

How does it work?

I have a one-line script removing a user from Active Directory. If I select the Ask OpenAI About it from context menu, it will tell me what it does:

Pretty well done. Let’s try to use it against more difficult one with unusual (for PowerShell) .Net classes like Garbage Collector and Semaphore (if you are curious what it is, read about this script in my another article here: Synchronizing PowerShell scripts – control the flow):

Again, the provided summary is accurate. Now it’s your time to use PowerShell to integrate OpenAI GPT with context menu in Windows!

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