December 28, 2020

281 words 2 mins read

env for PowerShell

env for PowerShell

As a developer I find myself splitting my time between Windows and Linux terminals doing different tasks. I have a love/hate relationship with both, but there are some syntaxes that I would love to exist in both places. PowerShell has done a decent job of bringing over some of the simple commands to make life easier (ls, cat, pwd, rm, etc), but there is one that I always wanted…

env

I don't use it a ton, but when I need to check my environment variables I either need to google the command to do it, or load it up from the UI to see what's there. To make things even more confusing, there are multiple ways to accomplish this in PowerShell:

  • Get-ChiledItem env:
  • dir env:
  • ls env:

I just wanted a quick-and-dirty way to list the environment variables to see if a value has been set, and I wanted to simplify my workflow between PowerShell and Bash. To accommodate this I created a PowerShell alias so I could just type

env

and always list my environment variables regardless of which shell I'm in. I know I'm only saving 4 keystrokes, but not having to shift my mind to pick the right syntax helps keep me focused on what I'm doing.

To set this up, just run the following script in a PowerShell window:

#Make sure a profile exists, if not, create one
if ((Test-Path $Profile) -eq $false)
{
    Write-Host "Creating Pofile" -ForegroundColor Yellow
    New-Item -Path $Profile -Type file Force
}

#Add the function and setup the alias
Write-Host "Adding Alias To Profile" -ForegroundColor Yellow
Add-Content -Path $Profile -Value "`nFunction ListVars {ls env:}"
Add-Content -Path $Profile -Value "`nSet-Alias -Name env -Value ListVars"