在PowerShell中等同于Bash别名的内容

12

一个新手的PowerShell问题:

我想在PowerShell中创建一个与这个Bash别名完全等效的别名:

alias django-admin-jy="jython /path/to/jython-dev/dist/bin/django-admin.py"

在 tinkering with it so far 的过程中,我发现这非常难做到。

-PowerShell 别名只能与 PowerShell 命令 + 函数调用一起使用

-没有明确的方法允许对 PowerShell 函数调用传递无限数量的参数

-PowerShell 似乎会阻止 stdout


值得注意的是,我尝试了这里提出的解决方案:http://huddledmasses.org/powershell-power-user-tips-bash-style-alias-command/

并且在加载 PowerShell 时遇到了以下语法相关错误:


The term 'which' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spell
ing of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\Dan\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:9 char:27

+             $cmd = @(which <<<<  $_.Content)[0]
    + CategoryInfo          : ObjectNotFound: (which:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
3个回答

26

PowerShell别名不允许使用参数
它们只能引用命令的名称,可以是命令或函数的名称,也可以是脚本或可执行文件的名称/路径。

要实现您想要的功能,您需要定义一个函数

function django-admin-jy {
    jython.exe /path/to/jython-dev/dist/bin/django-admin.py @args
}

这里使用了自PowerShell 2.0起可用的一个特性,叫做参数splatting:你可以将@应用于引用数组或哈希表的变量名。
在这种情况下,我们将其应用于名为args自动变量,该变量包含所有参数(未绑定到显式声明的参数 - 请参阅about_Functions)。

如果要创建接受参数的别名函数的真正通用方法,请尝试以下操作:

function New-BashStyleAlias([string]$name, [string]$command)
{
    $sb = [scriptblock]::Create($command)
    New-Item "Function:\global:$name" -Value $sb | Out-Null
}

New-BashStyleAlias django-admin-jy 'jython.exe /path/to/jython-dev/dist/bin/django-admin.py @args'

2
使用函数的一个好处是,您可以获得自动完成参数名称(在 - 后按 tab 键)的功能,而这对于使用通用的 New-BashStyleAlias 设置别名时是不可用的。定义函数可能会比较冗长,但在配置文件中应该不会成为问题。 - orad

1

我曾经苦苦挣扎,但我已经编写了这个PowerShell模块:

https://www.powershellgallery.com/packages/HackF5.ProfileAlias

https://github.com/hackf5/powershell-profile-alias

开始使用,您可以通过以下方式安装:

在HTML中保留不变

Install-Module HackF5.ProfileAlias
Register-ProfileAliasInProfile

然后像这样使用它:
Set-ProfileAlias dkfeed 'Enter-Docker feed_app_container' -Bash

我自己已经使用它一段时间了,发现它相当有用。

(它只能在PS 7.0上运行,因为我是为自己编写的)。


1

函数可以有任意多的参数。您只需要使用$args来访问它们。

至于stdout问题:您具体遇到了什么情况?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接