代码之家  ›  专栏  ›  技术社区  ›  RaviLobo

PowerShell中的动态相关参数

  •  2
  • RaviLobo  · 技术社区  · 6 年前

    我需要用动态参数创建一个PowerShell函数 依赖的 ($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.
    

    我有单个动态参数($server$database)的代码 here 论坛也提出了类似的问题 here ,但到目前为止还没有人回答。

    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 回复  |  直到 6 年前
    推荐文章