使用带有标签和列表达式的多个变量时分割结果

问题描述 投票:0回答:1
$cluster = Get-ClusterResource -Cluster <server> |
           Select Name,Ownernode, ResourceType, State |
           Where-Object {$_.ResourceType -match 'SQL Server Availability Group'}
$cluster | Out-GridView

$Nodes = Get-ClusterNode -Cluster $Server |
         Select @{n='ClusterName';e={$_.Cluster}}, Name, State 
$Nodes | Out-GridView

从上面的命令,结果显示为(取决于行数)。

1. Name | Ownernode | ResourceType | State
2. Name | Ownernode | ResourceType | State
3. Name | Ownernode | ResourceType | State

因为我使用多个变量来存储结果,所以我将两个变量的列连接成一个:

$Res = @()
$Res = foreach ($Server in $Servers) {
    $cluster = Get-ClusterResource -Cluster <server> |
               Select Name, Ownernode, ResourceType, State |
               Where-Object {$_.ResourceType -match 'SQL Server Availability Group'} 
    $cluster

    $Nodes = Get-ClusterNode -Cluster $Server |
             Select @{n='ClusterName';e={$_.Cluster}}, Name, State 
    $Nodes

    New-Object -Type PSObject -Property @{
        Name  = $cluster.Name
        Owner = $cluster.Ownernode
        Node1 = $nodes.Name[0]
        Node2 = $nodes.Name[2]
    }
}
$Res | Select Name, Owner, Node1, Node2 | Out-GridView

这样做的问题是返回的结果被组合成一列而不是单独的行:

Name | Owner| Node1 | Node2
1.name,name,name | owner | node1 | node2 
powershell variables formatting
1个回答
0
投票

这是你的问题的两分钱:你的变量$cluster是一个集合资源的集合/列表,这就是为什么你在使用$cluster.Name时获得所有名称的列表。我想你想迭代这个资源列表,并为每个条目获取节点。我还改变了PSObject,每个资源和节点返回一行;不是两个或更多节点。

$Res = @()
$Res = foreach ($Server in $Servers) {
    $clusterResources = Get-ClusterResource -Cluster $server | Where-Object {$_.ResourceType -match 'SQL Server Availability Group'} 
    foreach($resource in $clusterResources) {
        $Nodes = Get-ClusterNode -Cluster $resource.Cluster

        foreach($Node in $Nodes) {
            New-Object -Type PSObject -Property @{
                Name  = $Node.Cluster
                Owner = $resource.Ownernode
                Node = $Node.Name
            }
        }
    }
}
$Res | Out-GridView
© www.soinside.com 2019 - 2024. All rights reserved.