marc
marc

Reputation: 3338

In PowerShell, how can I list all environmental variables without using Get-ChildItem or Get_Item?

I'm writing a simple PowerShell script and want to dump all environmental variables/values. Something simple like

gci env:* | sort-object name

seemed liked a good start. But this didn't work for me.

Where things seem to get wacky is that my script is called from a job run by scheduler, both of which set environmental variables configured by other developers.

So, when I use Get-ChildItem as shown above, I get:

gci : An item with the same key has already been added.

Finally, my question: How can I get the environmental variables, ideally both names and values, to see which one(s) have been added incorrectly?

Upvotes: 3

Views: 11994

Answers (3)

Luis Rita
Luis Rita

Reputation: 392

A simple-to-remember command is:

dir Env:

Upvotes: 10

Himanshu Tripathi
Himanshu Tripathi

Reputation: 9

For Powershell version 5.1.19041.906, below commands works fine.

gci env:* | sort-object name

Alternatively you can use below command for your requirement.

[System.Environment]::GetEnvironmentVariables()

Upvotes: 0

filimonic
filimonic

Reputation: 4644

There are 3 scopes of what is called Environment Variables:

[System.EnvironmentVariableTarget]::Machine
[System.EnvironmentVariableTarget]::User
[System.EnvironmentVariableTarget]::Process

To get list of variables, you can use

[System.Environment]::GetEnvironmentVariables($scope)
[System.Environment]::GetEnvironmentVariables() # This will mix all scopes in one output

To set variable, you can use

[System.Environment]::SetEnvironmentVariable($varName, $varValue, $scope)

If $scope is Machine or User, it will try to store data, otherwise it will trow an exception.


$Env: is actually a virtual PowerShell drive and environment variables are items on it. There is a special provider Get-PSProvider -PSProvider Environment that implements this method of accessing to environment in powershell.

You can run Get-ChildItem -Path 'Env:\' and this is exactly the same as [System.Environment]::GetEnvironmentVariables() without specifying scope.

Upvotes: 4

Related Questions