PowerShell对嵌套工作流的高级参数验证

时间:2017-10-27 13:06:44

标签: validation powershell parameters workflow

我们希望在嵌套的PowerShell工作流程中使用高级参数验证 Normaly并不起作用。

workflow child
{
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]$Identity,
        [ValidateNotNullOrEmpty()]
        [System.String]$Server,
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.PSCredential]$Credential
    )
}

workflow parent
{
    child -Identity 'Test' -Server $null
}

parent

At line:17 char:5
+     child -Identity 'Test' -Server $null
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Advanced parameter validation is not supported on nested workflows.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : ParameterValidationNotSupportedOnNestedWorkflows


还有其他方法可以在此post中验证参数吗?

我尝试过这样做,但首先解决脚本块中$using:的问题并且我找不到一种方法来获取所有输入参数,例如$PSBoundParameters正常的脚本。

workflow parent
{
    child -Identity 'Test' -Server $null
}

workflow child
{
    param
    (
        [System.String]$Identity,
        [System.String]$Server,
        [System.Management.Automation.PSCredential]$Credential
    )

    #Validate input parameters
    InlineScript
    {
        [System.String]$Command = 'Validate-InputParameters'
        function Validate-InputParameters
        {
            param
            (
                [Parameter(Mandatory = $true)]
                [ValidateNotNullOrEmpty()]
                [System.String]$Identity,
                [ValidateNotNullOrEmpty()]
                [System.String]$Server,
                [ValidateNotNullOrEmpty()]
                [System.Management.Automation.PSCredential]$Credential
            )

            Write-Host -Object 'Successfully validated!'
        }

        if ($using:Identity -ne $null)
        {
            $Command += ' -Identity $using:Identity'
        }

        if ($using:Server -ne $null)
        {
            $Command += ' -Server $using:Server'
        }

        if ($using:Credential -ne $null)
        {
            $Command += ' -Credential'
        }
        $Command
        $ScriptBlock = [System.Management.Automation.ScriptBlock]::Create($Command)
        $ScriptBlock.Invoke()
    }
}

parent
Validate-InputParameters -Identity $using:Identity
Exception calling "Invoke" with "0" argument(s): "A Using variable cannot be retrieved. A 
Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script 
workflow. When it is used with Invoke-Command, the Using variable is valid only if the script 
block is invoked on a remote computer."
At child:16 char:16
+ 
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : RuntimeException
    + PSComputerName        : [localhost]

0 个答案:

没有答案