In a previous post, “How To Read Environment Variables In PowerShell”, we looked at how to read environment variables in PowerShell.

In a subsequent post, “About Environment Variable Scopes”, we learned that environment variables are scoped.

In this post, we will look at how to write or set environment variables in PowerShell.

Process Scoped Variables

To set process-scoped variables, there are three ways:

The first is to use the $env variable.

$env:Mood = "Happy"

The next method is to use the set-item cmdlet.

Set-Item -Path Env:Mood -Value "Happy"

The last method is to invoke the static .NET methods.

[Environment]::SetEnvironmentVariable('Mode', 'Happy')

User Scoped Variables

Setting user-scoped environment variables depends on your operating system.

For windows you invoke the .NET Environment object and set your scope to “User

[Environment]::SetEnvironmentVariable("Mood", "Sad", "User")

For macOS & Unix, there is no direct equivalent.

Machine Scoped Variables

User Scoped Variables

Setting machine-scoped environment variables depends on your operating system.

For windows you invoke the .NET Environment object and set your scope to “Machine”.

[Environment]::SetEnvironmentVariable("Mood", "Sad", "Machine")

For this to work, you must invoke it from an elevated terminal with administrative rights.

For macOS & Unix, there is no direct equivalent.

The closest is to export the variables like this:

export Mood=Crying

To have them persist across restarts, append this to your $profile (depending in your shell)

Happy hacking!