Reputation: 6883
I am trying to be consistent in my code, using either $env:
or [Environment]
, but not a mix. However, I am seeing some inconsistencies in what seems to be implemented.
So [Environment]::UserName
and $env:userName
both work fine. $env:computerName
works, but [Environment]::COMPUTERNAME
doesn't. Oddly [Environment]::MachineName
does, despite the fact that [Environment]::GetEnvironmentVariables()
says [Environment]::COMPUTERNAME
is present, not [Environment]::MachineName
. Also, [Environment]::GetEnvironmentVariables()
says [Environment]::USERPROFILE
should work, but it actually returns nothing.
When I look at the Microsoft doc here about properties of the [Environment]
type I do see MachineName
, along with UserName
, and no mention of UserProfile
. So, obviously that IS the right resource. But that begs the question, why does [Environment]::GetEnvironmentVariables()
return such inconsistent information?
Upvotes: 2
Views: 50
Reputation: 1855
[Environment]
or more specifically [System.Environment]
is restricted to the static methods and properties documented at the link you provided.
[Environment]::GetEnvironmentVariables
returns a list of environment variables and their values, some of which the operating system sets for you ("COMPUTERNAME"
, "USERNAME"
, etc.) which do overlap with some of the [Environment]
properties, but also include any environment variables applications have added or users have added typically using System Properties / Advanced / Environment Variables.
[Environment]::USERPROFILE
doesn't return anything because USERPROFILE
isn't a static property on the [System.Environment]
class. You can list all the static properties like this:
[System.Environment] | Get-Member -MemberType Properties -Static
You can add new environment variables that will then be returned using [Environment]::GetEnvironmentVariables
. For example:
$env:TEST = "This is a test"
More good info and examples of environment variables (not the [Environment]
class) here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_environment_variables?view=powershell-7.1
Upvotes: 1