在SQL服务器上获取动态数据库参数 [英] Getting a dynamic database parameter on a SQL server

查看:11
本文介绍了在SQL服务器上获取动态数据库参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建带有两个参数的ps函数:$SERVER&;$DATABASE。我需要根据第一个参数($SERVER)自动填充$DATABASE参数(动态验证集)

我从here

获得了大部分代码

然而,它不起作用。我到底做错了什么?任何洞察力都是非常值得赞赏的。谢谢。

function Get-databases {
    [CmdletBinding()]
    Param(
        # Any other parameters can go here              

        [Parameter(Mandatory)][string] $Server 

    )

    DynamicParam {
            # Set the dynamic parameters' name
            $ParameterName = 'Database'

            # Create the dictionary 
            $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary

            # Create the collection of attributes
            $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]

            # Create and set the parameters' attributes
            $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
            $ParameterAttribute.Mandatory = $true
            $ParameterAttribute.Position = 1

            # Add the attributes to the attributes collection
            $AttributeCollection.Add($ParameterAttribute)

            # Generate and set the ValidateSet             
            $arrSet = (Invoke-Sqlcmd -ServerInstance $server  -query 'select name from sys.databases order by 1'   -ConnectionTimeout 60 -QueryTimeout 99999).name                         
            $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)

            # Add the ValidateSet to the attributes collection
            $AttributeCollection.Add($ValidateSetAttribute)

            # Create and return the dynamic parameter
            $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
            $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
            return $RuntimeParameterDictionary
    }

    begin {
        # Bind the parameter to a friendly variable
        $db = $PsBoundParameters[$ParameterName]
    }

    process {
        # Your code goes here
        $db 

    }

}

推荐答案

如果您在DynamicParam ValiateSet属性中有Invoke-SqlCmd,您的制表符完成将执行整个Invoke-SqlCmd以进行验证,这是非常昂贵的w.r.t性能。

您可以在不使用制表符完成的情况下向数据库提供一些xyz值,您将看到它正在验证输入,但花费的时间很少,因为它将执行Invoke-SqlCmd以进行验证。

因此,我建议不要使用DynamicParam或避免在DynamicParam中进行验证,您可以在Begin块中进行显式验证。

这篇关于在SQL服务器上获取动态数据库参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆