Powershell如何连接多个结果

时间:2017-10-03 16:57:46

标签: sql-server powershell cluster-computing

从服务器列表(Servers.txt)中,我得到每个服务器的AG和监听器名称。

为了能够获得-ClusterParameter HostRecordTTL, RegisterAllProvidersIP我需要连接AG_Name + Listener_Name:
例:Get-ClusterResource -cluster "SERVER001" -name "AGNAME001_ISTENER001" | Get-ClusterParameter HostRecordTTL,RegisterAllProvidersIP

问题是当我为同一台服务器提供超过01 AG / Listener时 如何为同一服务器返回的每一行连接AG + Listener?

之前我使用的是TOP 1,但它只返回了第一行,而且我得到的服务器超过04 AG /听众。

$output = foreach ($cluster in GC "D:\Servers_List.txt")
{
    $AGName =  invoke-sqlcmd -Serverinstance $cluster -query "select top 1 left(name,25) as ' ' from sys.availability_groups order by 1" 
    $LNName =  invoke-sqlcmd -Serverinstance $cluster -query "select top 1 left(dns_name,25) ' ' from sys.availability_group_listeners order by 1" 
    $NetworkName = "$($AGName." ")_$($LNName." ")" 
    Get-ClusterResource -cluster $cluster -name $NetworkName | Get-ClusterParameter HostRecordTTL,RegisterAllProvidersIP 
} 
$output | Export-Csv 'D:\RAPIPHRTTL.csv' -NoType

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

$output = foreach ($cluster in GC "D:\Servers_List.txt")
{
    #modify your querys like necessary + rename columns
    $AGNames =  invoke-sqlcmd -Serverinstance $cluster -query "select left(name,25) as AG from sys.availability_groups order by 1" 
    $LNNames =  invoke-sqlcmd -Serverinstance $cluster -query "select left(dns_name,25) as LN from sys.availability_group_listeners order by 1" 

    #build list combination    
    $NetworkNames=$AGNames | foreach{$AG=$_.AG; $LNNames | foreach{"{0}_{1}" -f $AG, $_.LN}    }

    #use list combination for get cluster ressources   
    $NetworkNames | foreach{
    Get-ClusterResource -cluster $cluster -name $_ | Get-ClusterParameter HostRecordTTL,RegisterAllProvidersIP 
    }

} 
$output | Export-Csv 'D:\RAPIPHRTTL.csv' -NoType

答案 1 :(得分:0)

更好的解决方案,构建到您的查询中(我认为只有一个查询对性能更好)

$output = foreach ($cluster in GC "D:\Servers_List.txt")
{
    #only one query calculate all combinations and build string name ressources
    $NetworkNames =  invoke-sqlcmd -Serverinstance $cluster -query "select left(f1.name,25) + '_' + left(f2.dns_name,25) as AGLN from sys.availability_groups f1 cross join sys.availability_group_listeners f2 " 

    $NetworkNames | foreach{
    Get-ClusterResource -cluster $cluster -name $_.AGLN | Get-ClusterParameter HostRecordTTL,RegisterAllProvidersIP 
    }

} 
$output | Export-Csv 'D:\RAPIPHRTTL.csv' -NoType

注意:您可以像这样简化代码:

$Query="select left(f1.name,25) + '_' + left(f2.dns_name,25) as AGLN from sys.availability_groups f1 cross join sys.availability_group_listeners f2 "

GC "D:\Servers_List.txt" | foreach{
    $cluster=$_
    invoke-sqlcmd -Serverinstance $cluster -query $Query | foreach{
    Get-ClusterResource -cluster $cluster -name $_.AGLN | Get-ClusterParameter HostRecordTTL,RegisterAllProvidersIP
    }

} | Export-Csv 'D:\RAPIPHRTTL.csv' -NoType