1

我有一个循环遍历 3 个服务器列表的 PowerShell 脚本。运行 SQL 脚本Invoke-Sqlcmd并将结果集存储到 variable $DS。在循环结束时,我返回带有 with 的记录$DS.Tables.Rows

但是结果集正在混合在一起。我尝试使用Write-Host消息来分解结果。但它们仍然混合在一起。

为什么结果在输出中混合在一起?

如何分离每个循环之间的输出?

谢谢

在此处输入图像描述

在此处输入图像描述

对象类型

$DS | gm ............... TypeName: System.Data.DataSet

$DS.Tables | gm ........ TypeName: System.Data.DataTable

$DS.Tables.Rows | gm ... TypeName: System.Data.DataRow

脚本

#########################>

# SQL servers
$PCList= @("GCOD139","GCOD039","GCOP039") 
Write-Host ($PCList -join ", ") 

# Query multiple servers
foreach ($PC in $PCList) {

    Write-Host ($PC + "...") -ForegroundColor Yellow

    # SQL parameters
    $Params = @{
        'ServerInstance' = $PC;  
        'Database' = 'master';
    #   'Username' = 'svcBIPOC';
    #   'Password' = 'bipoc2020*';
    #   'InputFile' = "C:\ScriptFolder\TestSqlCmd.sql"
        'Query' = '
            SELECT 
                [Server]= @@SERVERNAME
                --MB to GB
                , REPLACE(name, ''MB'', ''GB'')
                ,[value]= CAST(value as int)/1000
                , [value_in_use]= CAST(value_in_use as int)/1000
                --, value, value_in_use, [description]
            FROM sys.configurations
            WHERE name like ''%server memory%''
            ORDER BY name desc 
            OPTION (RECOMPILE);
        '
    }

    # Capture SQL Dataset
    # (Get-Date).ToSTring('s')  + " SQL query start..."
    $DS = Invoke-Sqlcmd @Params -As DataSet
    #(Get-Date).ToSTring('s')  + " SQL query end..."

    Write-host "-----"
    Write-host "SQL"

    sleep -Seconds 5
    $DS.Tables.Rows
    sleep -Seconds 5

}


#########################
4

1 回答 1

1

停止使用Write-Host来传达进度信息 -Write-Progress改为使用它!

$PCList= @("GCOD139","GCOD039","GCOP039") 
Write-Progress -Activity "Query servers" -Status "About to query: $($PCList -join ", ")"

# Query multiple servers
foreach ($PC in $PCList) {

    Write-Progress -Activity "Query servers" -Status "Querying: $PC"

    # SQL parameters
    $Params = @{
        'ServerInstance' = $PC;  
        'Database' = 'master';
    #   'Username' = 'svcBIPOC';
    #   'Password' = 'bipoc2020*';
    #   'InputFile' = "C:\ScriptFolder\TestSqlCmd.sql"
        'Query' = '
            SELECT 
                [Server]= @@SERVERNAME
                --MB to GB
                , REPLACE(name, ''MB'', ''GB'')
                ,[value]= CAST(value as int)/1000
                , [value_in_use]= CAST(value_in_use as int)/1000
                --, value, value_in_use, [description]
            FROM sys.configurations
            WHERE name like ''%server memory%''
            ORDER BY name desc 
            OPTION (RECOMPILE);
        '
    }

    # Capture SQL Dataset
    $DS = Invoke-Sqlcmd @Params -As DataSet
    $DS.Tables.Rows
}

Write-Progress -Activity "Query servers" -Completed

现在进度消息不会干扰函数的实际输出

于 2020-08-07T13:46:47.600 回答