2011-01-11 35 views
5

是否可以將一些元數據屬性分配給PowerShell宏?我有一組宏,我想將它們封裝到邏輯組。我想是這樣的:Powershell屬性?

[UnitTest] 
function Do-Something() 
{ 
... 
} 

,然後通過所有加載宏在運行時和他們篩選出像:

$macrosInRuntime = Get-Item function: 
$unitTestMacros = $macrosInRuntime | 
    ? {$_.Attributes -contain "UnitTest"} # <-- ??? 
foreach ($macro in $unitTestMacros) 
{ 
    .... 
} 

我將不勝感激任何幫助

回答

5

有趣的問題......有沒有這樣的功能屬性,AFAIK。但我認爲,採用基於評論的幫助屬性(可能甚至根本不知道,但我不太確定)是一種半傻的方式。

<# 
.FUNCTIONALITY 
    TEST1 
#> 
function Do-Something1 
{} 

<# 
.FUNCTIONALITY 
    TEST2 
#> 
function Do-Something2 
{} 

Get-ChildItem Function: | %{ 
    $fun = $_.Name 
    try { 
     Get-Help $fun -Functionality TEST* | %{ 
      switch($_.Functionality) { 
       'TEST1' { "$fun is for test 1" } 
       'TEST2' { "$fun is for test 2" } 
      } 
     } 
    } 
    catch {} 
} 

輸出:

Do-Something1 is for test 1 
Do-Something2 is for test 2 

也許這種做法可能會在某些情況下非常有用。

另見COMMENT-HELP基於關鍵字的幫助:

man about_Comment_Based_Help 

UPDATE 雖然上面的答案被接受,我仍然無法與它很高興。這是另一種絕對不是黑客行爲的方法。它也有一個優點,請參閱評論。這種方法使用傳統名稱的額外別名。

# Functions to be used in tests, with any names 
function Do-Something1 { "Something1..." } 
function Do-Something2 { "Something2..." } 

# Aliases that define tests, conventional names are UnitTest-*. 
# Note: one advantage is that an alias can be defined anywhere, 
# right where a function is defined or somewhere else. The latter 
# is suitable in scenarios when we cannot modify the source files 
# (or just do not want to). 
Set-Alias UnitTest-Do-Something1 Do-Something1 
Set-Alias UnitTest-Do-Something2 Do-Something2 

# Get UnitTest-* aliases and extract function names for tests. 
Get-Alias UnitTest-* | Select-Object -ExpandProperty Definition 

# Or we can just invoke aliases themselves. 
Get-Alias UnitTest-* | % { & $_} 
2

組織和分組命令在PowerShell中是一個持續的困境。這是一直需要管理的事情。但是,如果您努力工作,則可以使用命名cmdlet和函數的一些最佳做法。你可能已經注意到所有的cmdlet都是動詞 - 名詞格式。 IE Get-ProcessSet-Item,等等。很多人做的是將第三部分添加到將名詞組合在一起的命令中。例如,在Active Directory的世界中,您沒有get-user,而是get-aduser

你可以做的一件事,它可能不是最漂亮的事情,是用你選擇的2或3個字母順序命名你的單元測試函數。比方說,你選擇了一些像UT這樣非常原始的單元測試。那麼你的功能將是

function Do-UTSomething { "Something was done" } 

一旦你把所有的UT功能,您可以使用Get-Command cmdlet的通過他們來遍歷像這樣

Get-Command *UT* -commandtype function 

此外,如果你去一個遠一點和將它們打包到一個模塊中,您可以更好地完成並按該模塊排序。

Get-Command -module MyUnitTest 

您可以通過使用

help about_modules 
+0

感謝的建議得到模塊的各種信息,但是這不是我的觀點。我已經在無法重命名的地方創建了傳播和宏集(因爲有很多其他依賴的宏正在使用它們) – 2011-01-11 18:35:50