Powershell Attributes?

Can I assign some metadata attributes to powershell macros? I have a set of macros and I want to encapsulate them in logical groups. I imagine something like:

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

and then pass all loaded macros at runtime and filter them as:

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

I will be grateful for any help

+5
source share
2 answers

An interesting question ... There are no such function attributes, AFAIK. But I think there is a semi-hacker way that uses comment-based help attributes (maybe not even hacks, but I'm not quite sure).

<#
.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 {}
}

Conclusion:

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

Perhaps this approach may be useful in some scenarios.

See also the SEQUENTIAL KEY SERVICES section RELATED TO:

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-* | % { & $_}
+5

- PowerShell. , . , , , . , , -. IE Get-Process, Set-Item .. , , , . , Active Directory get-user, get-aduser.

, , , - unit test 2 3 . , , UT unit test.

function Do-UTSomething { "Something was done" }

UT, Get-Command

Get-Command *UT* -commandtype function

, , .

Get-Command -module MyUnitTest

help about_modules
+2

All Articles