2011-07-29 36 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'仍然是第一個位置參數。 –

相關問題