0

I am trying to access environment variables using Powershell. The environment variables, which is out of my control, contain periods in this format:

ENVIRONMENT_VARIABLE.1

Therefor, upon assigning the value of the environment variable to a local variable, it looks like this:

$myvar = $env:ENVIRONMENT_VARIABLE.1

However, every time I try to retrieve this variable, it always leaves out the ".1", returning nothing.

I'm aware periods + Bash = no bueno, but again, this is out of my control and I need a work around. If it helps, I already tried this as well with no luck:

$myvar = ${env:ENVIRONMENT_VARIABLE.1}

I appreciate any and all help on this. Thanks!

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

1 Answers1

3

The last format you're using works for me:

PS> ls env:\fo*

Name                           Value
----                           -----
Foo.1                          bar.1


PS> ${env:foo.1}
bar.1
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • OK - it's working for me too. Which leads me to what is really going on on my end. My code is in a while loop where Foo.1 is replaced by Foo.$i - $i being an incremented variable - leading my code to look like this: ${env:foo.$i} . Sorry for my vagueness. The real problem is why the $i is not resolving to an integer. – user1068261 Apr 03 '12 at 03:27
  • Anything inside curlies will not be normally evaluated such as the `.` to dereference a property or `$` to reference a variable. Try this instead `set-item "env:\foo.$i" bar.2`. Note that you won't be replacing the env var but will be creating a new one. You can always use `remove-item` to remove the old env var. – Keith Hill Apr 03 '12 at 04:50
  • Hmmm, I don't know if I'm following you. I don't want to set/remove/manipulate an env var. All I want is the value of that env var to run a job later. Is there a way to do this? – user1068261 Apr 03 '12 at 11:53
  • 1
    @user1068261 Ah then try `get-item "env:\foo.$i"`. – Keith Hill Apr 03 '12 at 13:53
  • Well, now it doesn't break =) But now it returns 'System.Collections.DictionaryEntry'. Gotta look up what that means. Thanks for the get-item bit. Didn't know you could set that to a variable. – user1068261 Apr 03 '12 at 14:06
  • 1
    @user1068261 The *-Item and *-ItemProperty cmdlets work on various PowerShell providers including the file system provider, registry provider and even the Environment provider. That is the env:\ behaves kind of like a drive. You can `cd` to it. You can even use rename-item and copy-item on environment variables. – Keith Hill Apr 03 '12 at 14:52