0

I created a .env file to host some api authentication keys for my various python and powershell scripts. I'm trying to get my powershell script to read the file and set the variables, but it doesn't seem to work. This is the command I'm using to set the variables, adapted from this answer.

switch -File .\wkspaces\IT-Scripts\New-UserCredentials.env {
    default {
      $name, $value = $_.Trim() -split '=', 2
      if ($name -and $name[0] -ne '#') { # ignore blank and comment lines.
        Set-Item "Env:$name" $value
      }
    }
  }

When I try to call the variable, it's just blank as if it doesn't exist. I am not using any spaces between the name and value in the .env file.

mklement0
  • 382,024
  • 64
  • 607
  • 775
TL_Arwen
  • 21
  • 1
  • 6

1 Answers1

1

The code in your question, which defines environment variables based on .env files, is sound.

However, accessing (the resulting) environment variables, using namespace variable notation via $env:, situationally requires enclosing the environment-variable names in {...}, namely if the names happen to contain characters that aren't by default recognized as part of an identifier by PowerShell.

For instance, the following defines an environment variable named foo-bar, with value baz, using PowerShell's environment provider:

Set-Item 'Env:foo-bar' 'baz'

Because foo-bar by default isn't recognized as an identifier by PowerShell, due to the embedded - character - be it as the name of a regular (shell-only) variable ($ prefix) or that of an environment variable via namespace variable notation ($env: prefix) - enclosure of the name, including the namespace prefix, if any, in {...} is required:

# Note: Without {...} enclosure, this would fail.
${env:foo-bar}  # -> 'baz'
mklement0
  • 382,024
  • 64
  • 607
  • 775