如何在中间编写带参数的PowerShell别名?

时间:2010-11-12 15:49:43

标签: powershell g++ alias

我正在尝试设置Windows PowerShell别名,以便使用某些参数运行MinGW的g ++可执行文件。但是,这些参数需要在文件名和其他参数之后。我不想经历尝试设置功能和所有这些的麻烦。有没有办法简单地说出这样的话:

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

或沿着这些方向的东西?我对PowerShell并不熟悉,而且我很难找到解决方案。任何人吗?

4 个答案:

答案 0 :(得分:93)

你想要使用函数,而不是像Roman所提到的别名。像这样:

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

试试这个,这是一个简单的例子:

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

您可能还希望将此文件放在您的配置文件中,以便在运行PowerShell时使其可用。您的个人资料文件的名称包含在$profile

答案 1 :(得分:5)

没有内置的这种方式。恕我直言,包装函数是到目前为止最好的方法。但我知道发明了一些变通方法,例如:

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

答案 2 :(得分:2)

这是一个示例函数,它将根据调用方式执行不同的操作:

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}
}

答案 3 :(得分:1)

要构建一个函数,将其存储为别名,并将整个内容保留在您的配置文件中以供日后使用:

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

您已使用所需的别名替换ALIAS,并使用要执行的命令或字符串替换COMMANDS

当然,不是这样做,你可以(并且应该!)通过以下方式为上述做出别名:

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

以防万一你的大脑从所有递归(别名的别名等)转出来,将第二个代码块粘贴到你的PowerShell(并重新启动PowerShell)之后,使用它的一个简单例子是:

alias myEcho 'echo $args[0]'

或没有args:

alias myLs 'ls D:\MyFolder'

如果您还没有个人资料

如果您还没有个人资料,上述方法将会失败! 在这种情况下,请使用New-Item -type file -path $profile -force from this answer