Use ChatGPT with PowerShell using REST-API
Prerequisites
- PowerShell 7 Version or above
- OpenAI Account
To use OpenAI’s API, you will first need to generate an API token from your OpenAI account and save it for later use. Once you have your API token, you can use it to make requests via Postman and receive incredible responses. The Guided documentation provided by OpenAI also includes information on how to handle API responses. Before proceeding, it’s important to understand how the API works.
How to use Open API with Postman
From Postman, click on Import , and then Raw Test , and then paste the following raw test .
curl https://api.openai.com/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}'
This looks good , and easy, but how about a Plain text and a complete response from ChatGpt? Let's do it using PowerShell . Make sure you have PowerShell 7 version or above , because some PowerShell Modules i.e., Secret management and Secret Store are not working with lower version of the PowerShell .
How to install the PowerShell modules
To install the Secret Management module from the PowerShell Gallery, use the following command:
Install-Module -Name Microsoft.PowerShell.SecretManagement -Repository PSGallery
To install the Secret Store module from the PowerShell Gallery, use the following command:
Install-Module -Name Microsoft.PowerShell.SecretStore -Repository PSGalleryp
After installation , now we need to register the secret , use the following command :
Register-SecretVault -Name ChatGptAPI -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault
Now set the value of the secret , use the following command :
Set-Secret-Name ChatGptAPI -Secret "shhh its a secret"
Now you can pass this value to your PowerShell script , and it will automatically pick your API secret from the Secret Management.
Managing ChatGpt Using PowerShell and Rest API
To use the code from the Gist, you can simply open the files and read the code. If the Gist contains a script, you can run the script by using the .\script.ps1
command in PowerShell.
For example, if the Gist contains a script named script.ps1
, you can run the script using the following command:
.\script.ps1
Final Output
Conclusion
Although I am not an expert in the field of artificial intelligence and machine learning, I have found OpenAPI to be a useful tool for powering PowerShell projects. I have utilized it for fun and found it to be capable of handling larger projects as well.
Follow me on GitHub : https://github.com/adilshehzad786
Connect with me on LinkedIn : https://www.linkedin.com/in/adilshehzad7/