Set aliases in PowerShell using doskey macros
Asked Answered
G

1

6

Is this possible? I have tried this blog, but it doesn't work. I have a macrofile with about 50 or so doskey macros, which is used in cmd.exe.

I run something like:

doskey /exename=powershell.exe /macrofile=C:\macrofile.txt

or

doskey /exename=powershell.exe blah=echo blah

But trying the command blah gives an error:

blah : The term 'blah' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

If I list them with doskey /macros:powershell.exe however, they're all there.

Is there a way I can create 50 aliases in PowerShell to map to these macros? The Set-Alias cmdlet doesn't help much since the commands are more complex than calling a simple PowerShell cmdlet. There are posts that suggest creating functions in a .ps1 script, however, this would work only if I manually write 50 different functions for each of the 50 macros in the file. Also, this would involve maintaining two files - the macrofile for cmd and a PowerShell script which translates these into functions.

Gelid answered 19/1, 2017 at 3:26 Comment(3)
"But it doesn't work" - Can you be more specific?Revet
Thanks, edited question to include details.Gelid
I believe this works if you don't use PSReadLine module.Revet
R
4

The PSReadLine module (ships with PowerShell 5.0 or later) is not compatible with doskey, which relies on the native console input functions. I tested on Windows 10/PowerShell 5:

PS C:\> Remove-Module PSReadLine
PS C:\> doskey /exename=powershell.exe g=Get-Location
PS C:\> g

Path
----
C:\
Revet answered 20/1, 2017 at 1:8 Comment(2)
Verified! Works, thanks! It seems that Powershell 3.0 might also have the 'PsReadLine' module. I tried (on Win10): 'powershell -version 2.0' and 'powershell -version 3.0' without removing this module and the doskey macro worked on 2.0 but not 3.0.Gelid
FWIW, it's worth considering ditching doskey and the native console input features for the PSReadline module. I think the extra gained functionality is worth the switch.Revet

© 2022 - 2024 — McMap. All rights reserved.