我正在尝试设置 Windows PowerShell 别名来使用某些参数运行 MinGW 的 g++ 可执行文件。但是,这些参数需要位于文件名和其他参数之后。我不想经历尝试设置函数之类的麻烦。有没有一种方法可以简单地说:
alias mybuild="g++ {args} -lib1 -lib2 ..."
或者类似的东西?我对 PowerShell 不太熟悉,并且很难找到解决方案。有人吗?
您想要使用函数,而不是别名,正如 Roman 提到的那样。像这样的东西:
function mybuild { g++ $args -lib1 -lib2 ... }
要尝试一下,这里有一个简单的例子:
PS> function docmd { cmd /c $args there }
PS> docmd echo hello
hello there
PS>
您可能还想将其放入您的配置文件中,以便在运行 PowerShell 时可以使用它。您的配置文件的名称包含在
$profile
中。
没有内置这样的方法。恕我直言,包装函数是迄今为止最好的方法。但我知道发明了一些解决方法,例如:
要构建一个函数,将其存储为别名,并将整个内容保留在您的配置文件中供以后使用,请使用:
$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]'
或不带参数:
alias myLs 'ls D:\MyFolder'
如果您还没有个人资料,以上方法将会失败! 在这种情况下,请使用此答案中的
New-Item -type file -path $profile -force
。
这是一个示例函数,它将根据其调用方式执行不同的操作:
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}
}
几年前,我创建了一个 PowerShell 模块来执行此操作。它在画廊中并且是开源的。
我一直在寻找同样的经历。使用方法如下:
Add-Alias ls 'ls -force'
Add-Alias add 'git add'
我使用带有别名的包装函数:
function Invoke-BatAsCat { & (Get-Command bat).Source -pp ${Args} }
Set-Alias -Name 'cat' -Value Invoke-BatAsCat
最佳实践是使用 PowerShell 动词作为函数名称和别名。不过,为了简洁起见,我使用
$Args
而不是声明 param
。