How can I write a PowerShell alias with arguments in the middle?

I am trying to configure a Windows PowerShell alias to run the MinGW g ++ executable with certain parameters. However, these parameters should appear after the file name and other arguments. I don’t want to have difficulty trying to configure a feature and all that. Is there a way to just say something like:

alias mybuild="g++ {args} -lib1 -lib2 ..." 

or something like that? Not everyone is familiar with PowerShell, and it's hard for me to find a solution. Is anyone

+48
alias powershell g ++
Nov 12 2018-10-12
source share
3 answers

You want to use a function, not an alias, as Roman mentioned. Something like that:

 function mybuild { g++ $args -lib1 -lib2 ... } 

To try this, here is a simple example:

 PS> function docmd { cmd /c $args there } PS> docmd echo hello hello there PS> 

You can also put this in your profile so that it is available when PowerShell starts. The name of your profile file is contained in $profile .

+62
Nov 12 2018-10-12
source share

There is no such built-in way. IMHO, the wrapper function is the best way to go this far. But I know that some workarounds were invented, for example:

https://web.archive.org/web/20120213013609/http://huddledmasses.org/powershell-power-user-tips-bash-style-alias-command

+5
Nov 12 '10 at 16:35
source share

To create a function, save it as an alias and save it all in your profile later, use:

 $g=[guid]::NewGuid(); echo "function G$g { COMMANDS }; New-Alias -Force ALIAS G$g">>$profile 

where you replaced ALIAS with the alias you want, and COMMANDS with a command or command line to execute.

Of course, instead you can (and should!) Make an alias for the above:

 echo 'function myAlias { $g=[guid]::NewGuid(); $alias = $args[0]; $commands = $args[1] echo "function G$g { $commands }; New-Alias -Force $alias G$g">>$profile }; New-Alias alias myAlias'>>$profile 

Just in case, when your brain got inside out from the whole recursion (smoothing aliases, etc.), after inserting the second block of code into PowerShell (and restarting PowerShell), a simple example of its use:

 alias myEcho 'echo $args[0]' 

or without arguments:

 alias myLs 'ls D:\MyFolder' 

Iff you don't have a profile yet

The above method will fail if you do not have a profile yet! In this case, use the New-Item -type file -path $profile -force from this answer .

0
Sep 22 '17 at 20:03
source share



All Articles