Dynamic dependent parameters in PowerShell

时间:2018-11-13 14:20:08

标签: powershell dynamicparameters

I need to create a PowerShell function with dynamic parameters that are dependent on each other ($server, $database, $table).

1.  When the user picks $server,  parameter $database needs to be auto-populated. 
2.  And, depending on what value selected for $database the $table parameter needs to be  auto-populated.

I have the code for single dynamic parameter ($server $database) here. (This too was posted by me, with a bounty). Someone else on this Forum has asked a similar question here, but no one has answered so far.

Here's the code for single dynamic parameter:

import-module sqlps
function Get-Database {
    <# 
        .SYNOPSIS 
            Dynamic validationset of databases      

    #>  
    #Requires -Version 3.0
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)][string]$server

    )

    DynamicParam {

        $newparams = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
        $paramattributes = New-Object System.Management.Automation.ParameterAttribute
        $paramattributes.ParameterSetName = "__AllParameterSets"
        $paramattributes.Mandatory = $false
        $systemdbs = @("master", "msdb", "model", "SSIS", "distribution")

        $srv = New-Object 'Microsoft.SqlServer.Management.SMO.Server' "$server"
        $dblist = ($srv.Databases).name | Where-Object { $systemdbs -notcontains $_ }

        $argumentlist = @()

        foreach ($db in $dblist) {
            $argumentlist += [Regex]::Escape($db)
        }

        $validationset = New-Object System.Management.Automation.ValidateSetAttribute -ArgumentList $argumentlist
        $combinedattributes = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
        $combinedattributes.Add($paramattributes)
        $combinedattributes.Add($validationset)
        $Databases = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("Databases", [String[]], $combinedattributes)        
        $newparams.Add("Databases", $Databases)     
        return $newparams

    }

    process {

        $UserDb = $psboundparameters.Databases

        Write-Host "You picked: $UserDb"
    }
}

Clear-Host 
Get-Database -server 'YourServerName' -Databases 'DynamicallyPopulatedDatabases'

0 个答案:

没有答案