3

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?

3
  • 1
    Try this from PowerShell see if it works for you cmd /c SET | ConvertFrom-String -Delimiter '=' Commented Jun 2, 2021 at 4:20
  • 1
    Thanks Santiago - this worked for me and revealed the problem! If you submit an answer, I'll accept it. Thanks! Commented Jun 2, 2021 at 5:46
  • That's fine, glad it worked. Commented Jun 2, 2021 at 13:28

3 Answers 3

11

A simple-to-remember command is:

dir Env:
Sign up to request clarification or add additional context in comments.

2 Comments

That was easy...
It's worth noting that dir, gci, and ls are all aliases for Get-ChildItem in PowerShell and PowerShell Core.
4

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.

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.