tl;dr
Since you were looking for a friendly string representation of the environment-variable name-value pairs:
gci env: | oss
oss
is a built-in wrapper function for Out-String -Stream
, and therefore returns each name-value pair as its own string; pipe to Out-String
(without -Stream
) to get a single, multi-line string (albeit one that invariably and unexpectedly has a trailing newline - see GitHub issue #14444).
To list the names and values of all environment variables in PowerShell, sorted by name,[1] list the content (child items) of the env:
PowerShell drive using the Get-ChildItem
cmdlet (a built-in alias of which is gci
):
# 'gci' is a built-in alias of the 'Get-ChildItem' cmdlet.
# Avoid alias 'ls', because on Unix-like platforms
# it isn't defined and instead refers to the standard utility of that name.
# The output is implicitly *sorted by variable name*.
gci env:
# Use *wildcards* to list variables by *name pattern*; e.g, all whose
# name starts with "home"
gci env:home*
The above outputs objects, namely instances of [System.Collections.DictionaryEntry]
describing each variable as a name-value pair, with .Key
(.Name
) and .Value
properties. PowerShell's for-display formatting system automatically renders these in a friendly two-column format.
To list environment-variable names only:
gci env: -Name
# Alternative, using property access:
(gci env:).Name
To get a specific environment-variable's value, e.g. USERNAME
, it's easiest to use namespace variable notation:
# Output the value of environment variable "USERNAME"
$env:USERNAME
# Alternative, using gc (alias of Get-Content)
# Needed if the name is stored in a variable.
gc env:USERNAME
If you stringify these objects with (potentially implied) .ToString()
:
In Windows PowerShell, they uselessly stringify as their type name, i.e. as verbatim 'System.Collections.DictionaryEntry'
In PowerShell (Core) 7, they now more meaningfully stringify as '[<name>, <value>]'
Try with (%
is a built-in alias of the ForEach-Object
cmdlet):
gci env: | % tostring
# Ditto with Write-Host, which also uses .ToString() stringification
gci env: | Write-Host
If you want to stringify them as they would print to the display, using the friendly two-column format, use the Out-String
cmdlet:
# Outputs *friendly* string representations
gci env: | oss # 'oss' is a built-in wrapper function for 'Out-String -Stream'
Note: If you use Out-String
without -Stream
, you get a single, multi-line string as the output, though note that it will have a trailing newline.[2]
[1] Note that using Get-ChildItem
/ gci
with env:*
, i.e. wildcard character *
following the drive specification env:
- is not only unnecessary for getting all variables, it actually results in unsorted output.
[2] That a trailing newline is invariably appended is problematic, as discussed in GitHub issue #14444