---
title: "Set Windows Environment Variables for API Keys in PowerShell"
description: "Use $env: for a temporary key, setx or the System Properties dialog for a permanent one, then open a new terminal. Steps, checks and pitfalls for OPENAI_API_KEY."
url: https://cdnping.org/en/blog/windows-set-env-variable-api-key
language: en
published: 2026-11-23
category: "Developer tools"
tags: ["Windows","PowerShell","environment variables","API key","setx"]
source: cdnping.org
license: Free to quote and summarize with a link to the url above.
---
# Set Windows Environment Variables for API Keys in PowerShell

To set an environment variable on Windows temporarily, run `$env:OPENAI_API_KEY="your-key"` in PowerShell; it only applies to the current window. To keep it permanently, use `setx` or the built-in Environment Variables dialog, and then open a new terminal, because existing ones won't see the change. The rest of this article uses `OPENAI_API_KEY` as the example and covers both approaches, how to verify them, and the usual pitfalls.

Why bother? Official SDKs and many command-line tools read the key from an environment variable by default. OpenAI's libraries, for example, read `OPENAI_API_KEY`. Keeping the key in the environment means it doesn't live in your code or config files, so it's less likely to be committed to a repository by accident. The exact variable name depends on each tool's official documentation.

## What's the difference between temporary and permanent settings?

| Method | Scope | After closing the window | Good for |
| --- | --- | --- | --- |
| PowerShell `$env:` | The current PowerShell session and its child processes | Gone | Quick tests, leaving no trace |
| `setx` / `SetEnvironmentVariable` | Current user, written to the registry | Kept | Everyday development |
| "Environment Variables" dialog in system settings | User or system variables | Kept | People who prefer a GUI and want to inspect and edit values |

The key point: a permanent setting only affects processes started afterward. Terminals that are already open, and the integrated terminal inside your editor, won't pick up the new value automatically.

## How do I set it temporarily in PowerShell?

```powershell
$env:OPENAI_API_KEY = "sk-xxxx"
```

`sk-xxxx` is a placeholder; replace it with your own key. Any program you run in the same window can read it. To verify:

```powershell
echo $env:OPENAI_API_KEY
```

Note that this prints the key in plain text on screen. When verifying, it's better to check only the length or the first few characters, as shown below.

## How do I set it permanently from the command line?

### Using setx

```powershell
setx OPENAI_API_KEY "sk-xxxx"
```

`setx` writes the variable to the current user's environment. After it reports success, close the terminal and open a new one before it takes effect. A few common pitfalls:

- **The current window can't see it**: `setx` doesn't modify the current session. To use the key right away, also run `$env:OPENAI_API_KEY = "sk-xxxx"`.
- **Length limit**: `setx` limits the length of a single value (commonly cited as 1024 characters; check Microsoft's official documentation). API keys are normally far shorter, but if you use it to set a long `PATH`, the value may be truncated. Don't use `setx` to modify `PATH`.
- **Quotes and spaces**: Wrap the value in quotes if it contains spaces. Keys normally have none, but when copying, make sure you haven't picked up leading or trailing spaces or a newline.

### Using the .NET method

You can also do this in PowerShell. It works much like `setx` but doesn't have the truncation problem:

```powershell
[Environment]::SetEnvironmentVariable("OPENAI_API_KEY", "sk-xxxx", "User")
```

The third argument, `"User"`, means the current user. `"Machine"` changes a system-wide variable and requires administrator rights, which personal development usually doesn't need.

## How do I set it through the GUI?

1. Press the Win key, search for "environment variables", and choose "Edit environment variables for your account" (or press Win+R, run `sysdm.cpl`, and click "Environment Variables" on the Advanced tab). Menu wording varies slightly between Windows versions.
2. In the upper "User variables" section, click "New".
3. Enter `OPENAI_API_KEY` as the variable name and paste your key as the value.
4. Click OK all the way out to save.
5. Close and reopen your terminal and editor, then verify.

The advantage of the GUI is that you can see all existing variables, and a mistake is easy to delete. For personal use, put the key under "User variables" rather than "System variables", since the latter is visible to every account on the machine.

## How do I confirm it took effect?

In a **newly opened** PowerShell window:

```powershell
if ($env:OPENAI_API_KEY) { "Set, length " + $env:OPENAI_API_KEY.Length } else { "Not set" }
```

This confirms the variable exists without printing the key. If you're using cmd, it's:

```cmd
echo %OPENAI_API_KEY%
```

You can also send a minimal request with the official SDK or curl and see whether you get a 401. A 401 usually means the key wasn't read or is wrong; for other status codes, check the official documentation. If you suspect the service itself, check [OpenAI API status](/en/status/openai) first to rule out an outage on their side.

## It's set but I can't read it. What are the common causes?

- **The process wasn't restarted**: The integrated terminals in VS Code, JetBrains and other IDEs inherit their environment when the IDE starts. After changing a variable, quit the IDE completely and reopen it; closing the terminal panel isn't enough.
- **Typo in the variable name**: Names are case-insensitive on Windows, but underscores and letters still have to be right. If the tool expects a name other than `OPENAI_API_KEY` (another vendor's SDK, for instance), follow its official documentation.
- **User and system variables with the same name**: When both exist, the user variable normally wins over the system one. Check both places when troubleshooting.
- **Not visible in WSL**: WSL is a separate environment. Variables set in Windows don't automatically appear in the Linux subsystem; set them separately in your WSL shell config.

## What should I watch out for when storing a key?

Environment variables are safer than hardcoding a key, but they aren't perfectly safe.

- PowerShell records the commands you type in its history (the PSReadLine history file), so typing the key directly on the command line leaves it in that history. Using the GUI avoids this; if you use the command line, check and clear the history afterward.
- Don't post screenshots or command logs containing a key in group chats or issues.
- Use one key per project so you can revoke each one individually. For a fuller treatment, see [How to store an API key securely](/en/blog/store-api-key-securely); for teams, see [How teams should manage API keys](/en/blog/team-shared-api-key-management).
- If a key leaks, revoke it first and then check usage. The steps are in [What to do when an OpenAI API key leaks](/en/blog/openai-api-key-leaked-response).

## How do I use this with Codex, Claude Code and similar tools?

These command-line tools usually read environment variables too, or let you name the variable to read in a config file. In Codex's `config.toml`, for example, `env_key` can point to a variable name; for field syntax see the [Codex config.toml field reference](/en/blog/codex-cli-config-toml-reference). If you don't have a ChatGPT account, see [Can you use Codex without a ChatGPT account?](/en/blog/codex-without-chatgpt-account). For Claude Code login options, see [Claude Code: API key login or subscription login](/en/blog/claude-code-api-key-login).

If you're just getting started and don't have an overseas credit card, you may also want to look at AGI Plan (AGI Plan is a commercial partner of cdnping). It's a monthly-subscription gateway that aggregates models from multiple providers, payable in Chinese yuan with no overseas card required. To keep using tools such as Claude Code and Codex, you only change one endpoint address and put the key generated by the platform into the environment variable described above. It is not an officially authorized channel, and some models are available only outside China; see the [models page](https://agiplan.dev/models) for specifics. For getting started, see [AGI Plan quick start](https://agiplan.dev/startup).

## What should I do next?

1. Pick one method, set the variable, and confirm it with the length-check command above in a new terminal.
2. Run one minimal request to confirm it works end to end.
3. Check whether the key has been written into your code or committed to a repository. If so, revoke it and create a new one immediately.
4. Add local files such as `.env` to `.gitignore`.

Once it works, if requests feel slow, open the [cdnping home page](/en) to measure first-connection and round-trip times from your network to each model API, and then decide whether the problem is on your machine or on the path.
