Search code examples
sql-serverpowershellpowershell-2.0invoke-sqlcmd

Powershell Invoke-Sqlcmd doesn't capture all verbose output


I created following powershell (v2) script to execute query on target database and build another query/queries to be run:

$sql = @"
DECLARE @Tables CURSOR;
DECLARE @TableName NVARCHAR(200);

BEGIN
    SET @Tables = CURSOR FOR
    SELECT TABLE_NAME
    FROM test.INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE='BASE TABLE' 
    AND TABLE_NAME LIKE 'x%'

    OPEN @Tables 
    FETCH NEXT FROM @Tables 
    INTO @TableName
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'SELECT TOP 1 * FROM test.dbo.' + @TableName
        FETCH NEXT FROM @Tables 
        INTO @TableName 
    END; 

    CLOSE @Tables ;
    DEALLOCATE @Tables;
END;
"@
$ps = [PowerShell]::Create()
$ps.AddCommand("Invoke-Sqlcmd").AddParameter("Query", $sql).AddParameter("Verbose")
$ps.Invoke()

$sqlOutput = $ps.Streams.Verbose
$sqlOutputToRun = $nul
$sqlOutput | foreach {
    $sqlOutputToRun += ($_.ToString() + "`n")
}
$sqlOutputToRun = @"
$sqlOutputToRun
"@

$sqlOutputToRun

In the end of script I am printing queries that have to be executed, but unfortunately variable $sqlOutputToRun contains only about 3/4 expected output. I suppose that output is somehow cut because of the size, but I am not sure how I can extend it.

Do you know what is missing?


Solution

  • If you can't live without your cursor why you can't do something like this?

    $sql = "
    DECLARE @Tables CURSOR;
    DECLARE @TableName NVARCHAR(200);
    DECLARE @Results TABLE (ResultQuery NVARCHAR(MAX)) 
    
    BEGIN
        SET @Tables = CURSOR FOR
        SELECT TABLE_NAME
        FROM testdb.INFORMATION_SCHEMA.TABLES 
        WHERE TABLE_TYPE='BASE TABLE' 
        --AND TABLE_NAME LIKE 'x%'
    
        OPEN @Tables 
        FETCH NEXT FROM @Tables 
        INTO @TableName
        WHILE @@FETCH_STATUS = 0
        BEGIN
            INSERT INTO @Results (ResultQuery)
            SELECT 'SELECT TOP 1 * FROM test.dbo.' + @TableName
    
            -- PRINT 'SELECT TOP 1 * FROM test.dbo.' + @TableName
            FETCH NEXT FROM @Tables 
            INTO @TableName 
        END; 
    
        CLOSE @Tables ;
        DEALLOCATE @Tables;
    END;
    SELECT * FROM @Results;"
    $sqlOutputToRun = Invoke-Sqlcmd -query $sql
    $sqlOutputToRun