Handling Local Secrets with PowerShell: Using $env and Windows Environment Variables

Handling Local Secrets with PowerShell: Using $env and Windows Environment Variables

Managing sensitive information such as API keys, access tokens, and database credentials, is a crucial aspect of software development. Ensuring that these secrets are not exposed or compromised is of utmost importance, as it can lead to security breaches and unauthorized access to critical systems. To address this issue, developers often turn to a simple yet powerful technique: the use of environment variables.

The idea is, instead of hard-coding secrets directly into the code, engineers store them as environment variables on their local machines. These variables can then be accessed by applications (e.g., PowerShell) during runtime, allowing the software to utilize the necessary secrets but also without potentially exposing them when pushing to a remote location, for example.

By using environment variables, the secrets remain separate from the sourced codebase and can be easily managed and modified as needed without the risk of accidentally exposing them.

In this article, we'll show you how to create Windows environment variables and then access them from PowerShell.


Step 1: Set the Environment Variable(s) in Windows

From the Start Menu, search for "environment" and select the option titled "Edit the system environment variables" from the Control Panel.

At the bottom of the System Properties window, select "Environment Variables..." to create the variable within Windows.

Within the Environment Variables window, select "New..." to create the User environment variable. Give it a name and value, then select "OK".

Immediately after creating the variable, you should see it listed in the User variables.

Repeat this process to create multiple variables, then close out everything by selecting OK within each window.


Step 2: Accessing the Variable(s) from PowerShell

Open a new PowerShell window and type $env: followed by the variable name you created.

For example, this article created the variable HashnodeDemoEnvVariable, so, to access it from PowerShell you'd type $env:HashnodeDemoEnvVariable.

And that's it! You can now set secrets within Windows and then access them using $env: within your PowerShell scripts. Taking this approach will better ensure that your secrets remain protected while still being easily accessible within your scripts.


Please leave a comment if you have any questions or feedback!

Thanks for reading and happy scripting!