Powershell函数用于过滤的参数

时间:2016-08-20 14:49:04

标签: sql-server tsql powershell

我正在尝试编写一个从sql数据库中提取所有服务器的函数。它工作正常。我需要为每个列实现过滤,这样我就可以通过一个或多个过滤来调用该函数。

例如,如果我需要拉动所有UAT服务器,我应该能够编写类似这样的东西,它应该拉动所有UAT -

  

Get-SHservers -Enviornment" uat"

  

Get-Shservers -Enviornment" uat" -Application" App1"

或其任何组合

function Get-SHServers
{
    $connectionstring = (Get-SHJson "D:\config\configdb.json").value
    $server =  Get-SHSQLData $connectionstring -Query @"
    select 
        b.Name as ApplicationName, 
        a.Name as ServerName,   
        a.FQDN,
        c.Name ServerRole,
        e.Name as Enviornment,
        d.Name Domain,
        f.Name ServerRegion
    from 
            server a inner join Application b on a.ApplicationID = b.ID 
            left join ServerRole c on a.ServerRoleId = c.Id
            left join Domain d on a.DomainID = d.id
            left join Enviornment e on a.EnviornmentId = e.Id
            left join ServerRegion f on a.ServerRegionID = f.Id
        WHERE 1=1
    order by 1
    "@
    foreach($item in $server) {
        $output = [ordered] @{
                    ServerName = $item.ServerName
                    FQDN = $item.FQDN
                    ApplicationName = $item.ApplicationName
                    ServerRole = $item.ServerRole
                    Domain = $item.Domain
                    Enviornment = $item.Enviornment 
                    ServerRegion = $item.ServerRegion
        }
        $obj = new-object -TypeName PSObject -property $output
        $obj.psobject.TypeNames.Insert(0, "sh.config.server")
        write-output $obj
    }
    }

为了实现这种行为,我更倾向于在S​​QL中注入过滤器以获得性能原因吗? *我是否应该将7个不同的参数传递给函数,并在[if else]中验证是否传递了一个或多个参数并构造SQL,或者在Powershell中有更简单的方法来执行此操作*

此外,这里是Get-SHSQLData

的实现
  [CmdletBinding()] param(
    [Parameter(Mandatory=$true)][string]$Query,
    [Parameter(Mandatory=$true)][string]$connectionstring
    )

    $Connection = New-Object System.Data.SQLClient.SQLConnection
    $Command    = New-Object System.Data.SQLClient.SQLCommand
    $Adapter    = New-Object System.Data.SqlClient.SqlDataAdapter
    $DataSet    = New-Object System.Data.DataSet


    if ($Query.Trim() -eq '' -or $connectionstring.Trim() -eq ''){
        write-host 'Query and ConnectionString are Mandatory Parameter' -ForegroundColor Red;
        return;
    }
    #$connectionstring = "server=$servername;database=$DatabaseName;trusted_connection=true;pooling=false"
    $connection.ConnectionString = $connectionstring;
    $Connection.Open()
    $Command.Connection = $Connection
    $Command.CommandText = $Query
    $Adapter.SelectCommand = $Command
    $Adapter.Fill($DataSet) | out-NULL
    $Connection.Close()
    $Connection.Dispose()
    return $DataSet.Tables[0]

2 个答案:

答案 0 :(得分:1)

,你应该将7个不同的参数传递给函数,但是,没有,实际上没有更简单的方法,因为它已经非常简单了。以下是前两个参数的示例:

function Get-Stuff
{
     param
     (
         [string]$AppName,
         [string]$ServerName
     )

     $whereClause = '1=1'
     if ($AppName) { $whereClause += " AND ApplicationName = '$AppName'"}
     if ($ServerName) { $whereClause += " AND ServerName = '$ServerName'"}
     Write-Host $whereClause    # this line is debug output only
}

以下是一些证明其用途的例子:

PS> Get-Stuff
1=1

PS> Get-Stuff -AppName "my app"
1=1 AND ApplicationName = 'my app'

PS> Get-Stuff -Server 'localhost' -AppName 'big app'
1=1 AND ApplicationName = 'big app' AND ServerName = 'localhost'

(脚注: 请查看Invoke-SqlCmd,这样可以显着减少代码的大小。)

答案 1 :(得分:0)

尝试使用参数集。这样您就可以使用Get-SHservers -Set1Get-SHservers -Set2

Function SCCM-ScheduledReboot{
 [CmdletBinding(SupportsShouldProcess=$true,DefaultParameterSetName="ViewOnly")]
Param(
    [Parameter(ParameterSetName="ViewOnly")]
    [switch]$ViewOnly,
    [Parameter(ParameterSetName="CSV")]
    [switch]$CSV,
    [Parameter(ParameterSetName="Create")]
    [switch]$Create,
    [Parameter(ParameterSetName="Create")]
    [switch]$Email
)


    Switch($PSCmdlet.ParameterSetName){
        "ViewOnly"{
        ViewOnly
        }
        "CSV"{
        CSV
        }
        "Create"{
        Create
        }
    }
}#end sccm-scheduledreboot function

这里我创建了SCCM-ScheduledReboot函数,其中包含三个参数集。默认值为ViewOnly,当函数在没有param的情况下运行时,它将默认为ViewOnly。

接下来我可以使用SCCM-ScheduledReboot -CSV,该函数将调用CSV函数。

或者,您的函数可以有一个传递给here-string中包含的SQL查询的参数。

Function SCCM-ScheduledReboot{
 Param(
    [Parameter()]
    [string]$ServerQuery
)

$Here-String-Query = @"
<< Your SQL query here, include $ServerQuery >>
"@

}#end sccm-scheduledreboot function