ChatGPT解决这个技术问题 Extra ChatGPT

Display all environment variables from a running PowerShell script

I need to display all configured environment variables in a PowerShell script at runtime. Normally when displaying environment variables I can just use one of the following at the shell (among other techniques, but these are simple):

gci env:*
ls Env:

However, I have a script being called from another program, and when I use one of the above calls in the script, instead of being presented with environment variables and their values, I instead get a list of System.Collections.DictionaryEntry types instead of the variables and their values. Inside of a PowerShell script, how can I display all environment variables?


J
Jim Aho

Shorter version:

gci env:* | sort-object name

This will display both the name and value.


Could you explain why it behaves like that and how your command fixes it, please?
That's the sign of progress because env was too easy. Damn you M$ people.
I want to add that this behavior was something I encountered in PowerShell 4, but as of 5.1+ I can use the variants shown in the question within a script and expect it to display the variable name and value. Note that gci env: will now sort the variables by Name. though gci env:* does not.
V
Vlad Rudenko

Shortest version (with variables sorted by name):

gci env:

P
Peter Mortensen

I finally fumbled my way into a solution by iterating over each entry in the dictionary:

(gci env:*).GetEnumerator() | Sort-Object Name | Out-String

doesn't run on Linux for me. Are you missing gci to get the child items?
I haven't tried this on powershell core, but gci is in my answer. Note that this question is for [powershell] and not [powershell-core], so solutions may not work for the latter.
E
Emil

Short version with a wild card filter:

gci env: | where name -like 'Pro*'

You can also skip the pipeline and simply use a wildcard filter with Get-ChildItem. For example: gci env:Pro*
M
Mauricio_BR

I don't think any of the answers provided are related to the question. The OP is getting the list of Object Types (which are the same for each member) and not the actual variable names and values. This is what you are after:

gci env:* | select Name,Value

Short for:

Get-ChildItem Env:* | Select-Object -Property Name,Value

C
Christopher Scott

This command works also:

dir env:

dir and gci are both aliases for Get-ChildItem
W
WeihanLi

If you're using PowerShellCore, you can also use ls env:


What is list? I see no such command in PowerShell (Core) v7.2.4. Did you mean ls? If so, that's yet another alias for Get-ChildItem and also already stated in the question.
Yeah, it should be ls, sorry for the miss-leading, thanks for your correction @LanceU.Matthews