2

Entering $env:path at the prompt correctly returns:

C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps;...

Entering $env:Path -split ';' at the prompt correctly returns:

C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\WindowsPowerShell\v1.0\
C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps                                   
...

Entering doskey envpath=$env:Path -split ';' at the prompt causes some pretty weird stuff that I've asked elsewhere about cleaning up, but among other things appears to evaluate $env:Path at the time I'm defining the macro.

However the desired result is for it to evaluate $env:Path later, at the time I'm running the macro. How do I create a macro to do that?

DavidT
  • 655
  • 7
  • 19

1 Answers1

0
  • Don't try to use doskey.exe in PowerShell: To get it to work at all, you'd have to unload the module that handles interactive command-line editing in PowerShell, PSReadLine - which would take away a lot of useful features. See this answer for background information.

  • Instead:

    • Define the desired functionality as a function.

    • Add that function to your $PROFILE file, so that it is available by default in future PowerShell sessions.

The following demonstrates this technique:

# Make sure the $PROFILE file exists.
if (-not (Test-Path $PROFILE)) {
  $null = New-Item -Force $PROFILE
}

# Add the desired functionality as a function definition.
@'

function envpath { $env:Path -split ';' }
'@ | Add-Content $PROFILE

Note the use of a (verbatim) here-string (@'<newline>...<newline>'@), which makes embedding a function definition in a string syntactically easier, since no escaping of embedded quote characters is needed.

envpath will then be defined in future PowerShell sessions (unless the session was created with the CLI's -NoProfile switch).

mklement0
  • 382,024
  • 64
  • 607
  • 775