如何向scriptmethod添加标记,以便根据标记排除/包含它?

时间:2018-02-22 10:38:15

标签: powershell powershell-v3.0

我正在尝试在我的代码中执行所有脚本方法。但是应该从中排除很少的脚本方法。

function new-TestSuite {
$testsuite = [pscustomobject]@{

    Data1 = 'value1'
    Data2 = 'value2'

}

$testsuite | Add-Member -MemberType ScriptMethod -Name Testcase1 -Value { "Testcase 1" <# Code using Data1 #> }
$testsuite | Add-Member -MemberType ScriptMethod -Name TestCase2 -Value { "TestCase2" <# Code using Data2 #> }
$testsuite | Add-Member -MemberType ScriptMethod -Name teardown -Value { "teardown" <# Code using Data2 #> }
$testsuite | Add-Member -MemberType ScriptMethod -Name setup -Value { "setup" <# Code using Data2 #> }

$testsuite
}

function Invoke-Testcase
{
    [CmdletBinding()]
    param
    (
        $Testsuite,
        $testcase =$null,
        $Exclude = @("TearDown","Setup")
    )    
    if($Testsuite -eq $null)
    {
        throw "Test suite is null"
    }

    if($null -eq $testcase)
    {
        $ScriptMethods = $Testsuite.psobject.Methods | Where {$_ -is [psscriptmethod]} #| Foreach Invoke

        foreach($sm in $ScriptMethods)
        {
            if(-not ($Exclude -contains $sm.name))
            {
                $sm.Invoke() 
            }
            else
            {
                Write-verbose "scriptmethod $($sm.name) will not be executed as it is in exclude list"
            }
        }
    }
    else
    {
        foreach($tc in $testcase)
        {
            $Testsuite.psobject.Methods | Where {$_ -is [psscriptmethod] -And $_.Name -eq $tc } | foreach Invoke
        }
    }
}

Set-Alias -Name InvokeTestCase -Value Invoke-Testcase

$ts = new-TestSuite
InvokeTestcase $ts -verbose

InvokeTestcase $ts teardown

在上面的函数(Invoke-Testcase)中,我正在使用排除列表并实现它。但是如果不需要执行任何新方法,则必须更新excludelist。

如果有标签可以添加到scriptmethod属性中,它将有更多的控制来包含/排除。有没有办法为scriptmethod创建标记?

0 个答案:

没有答案