2011-07-29 33 views
10

如果我定义以下我可以使用Powershell中的[别名(“db”)]参数创建脚本吗?

[parameter(Mandatory = $true)] 
[alias("db")] 
[string]$database, 

然后我得到一个错误

Parameter alias cannot be specified because an alias with the name 'db' 
was defined multiple times for the command. 

这是真的,因为db已经是普遍-Debug参数的别名。
是否可以在不重命名参数的情况下定义此别名?

+2

这应该工作。听起来你有两个(或更多)具有相同别名的参数。 – Richard

回答

9

对不起,你不能。 -Debug是一个常用参数,因此-Debug-db是几乎包括您自己编写的函数在内的所有可用交换机。正如错误告诉你的那样,它已经被定义了。

即使有可能绕过去取消定义内置别名,即unexpectantly改变别人像test-db -db呼叫谁经常使用-db而不是-Debug意义。他们期望它启用调试输出,而不是指定不同的参数。

考虑一下这个功能:

function test-db{ 
    param(
    [parameter(mandatory=$true)] 
    [string]$database) 
    write-host 'database' $database 
    write-debug 'debugging output' 
} 

现在有了test-db servertest-db -db servertest-db server -db调用它。第一个不做write-debug,而另外2个做,不管-db是哪里。你也不能定义一个单独的参数[string]$db(或重命名$database$db),因为PowerShell的给你这个错误:

Parameter 'db' cannot be specified because it conflicts with the parameter alias of the same name for parameter 'Debug'.

更多信息这一点,每MSDN

In addition to using the AliasAttribute attribute, the Windows PowerShell runtime performs partial name matching, even if no aliases are specified. For example, if your cmdlet has a FileName parameter and that is the only parameter that starts with F, the user could enter Filename, Filenam, File, Fi, or F and still recognize the entry as the FileName parameter.

+1

谢谢,这是有道理的(虽然是不幸的)。 –

+0

为了确切的原因,powershell总是会进行部分名称匹配,我们编写几乎总是使用完整参数名称的脚本。有关使用内置参数的更多信息,请参阅cmdletbinding()属性。 http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/07/weekend-scripter-cmdletbinding-attribute-simplifies-powershell-functions.aspx –

+0

哇,多么愚蠢的假设 - DB应该别名-debug - 因为,谁不希望-DB参数表示_database_? – fourpastmidnight

-2
function test-db { 
    param(
    [parameter(Mandatory = $true)] 
    [string]$database=[string]$db 
) 
    $PSBoundParameters["database"] 
} 

PS> test-db -database srv 
PS> test-db -db srv 
+1

这为什么有效?除非我错过了一些明显的东西,它看起来像没有记录的东西 –

+1

这也适用于'test-db srv -db'。这里有什么不对...... –

+1

添加“$ db”和“$ database”的打印,你会发现'$ db'永远不会以这种方式分配。它仍然是'-Debug'的缩写,因此在'-db srv'和'srv -db'中,'srv'仍然是第一个位置参数。 –

相关问题