我如何编写一个 PowerShell 别名,中间有参数?

我正在尝试设置一个 Windows PowerShell 别名,用特定的参数运行 MingW 的 g + + 可执行文件。但是,这些参数需要位于文件名和其他参数之后。我不想费力去设置函数之类的东西。有没有一种简单的说法,比如:

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

或者类似的东西?我对 PowerShell 不是很熟悉,而且很难找到解决方案。有人吗?

47582 次浏览

There is not such a way built-in. IMHO, a wrapper function is the best way to go so 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

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

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

To try this out, here's a simple example:

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

You might also want to put this in your profile in order to have it available whenever you run PowerShell. The name of your profile file is contained in $profile.

To build an function, store it as an alias, and persist the whole thing in your profile for later, use:

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

where you have replaced ALIAS with the alias you want and COMMANDS with the command or string of commands to execute.

Of course, instead of doing that you can (and should!) make an alias for the above by:

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 your brain got turned inside out from all the recursion (aliasing of aliases, etc.), after pasting the second code block to your PowerShell (and restarting PowerShell), a simple example of using it is:

alias myEcho 'echo $args[0]'

or without args:

alias myLs 'ls D:\MyFolder'

Iff you don't have a profile yet

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

This is a sample function that will do different things based on how it was called:

Function Do-Something {
[CmdletBinding()]
[Alias('DOIT')]
Param(
[string] $option1,
[string] $option2,
[int] $option3)
#$MyInvocation|select *|FL
If ($MyInvocation.InvocationName -eq 'DOIT'){write-host "You told me to do it...so i did!" -ForegroundColor Yellow}
Else {Write-Host "you were boring and said do something..." -ForegroundColor Green}
}

Creating a 'filter' is also an option, a lighter alternative to functions. It processes each element in the pipeline, assigning it the $_ automatic variable. So, for instance:

filter test { Write-Warning "$args $_" }
'foo','bar' | test 'This is'

returns:

WARNING: This is foo
WARNING: This is bar