Powershell Invoke-Sqlcmd 不捕获所有详细输出

Powershell Invoke-Sqlcmd doesn't capture all verbose output

我创建了以下 powershell (v2) 脚本来在目标数据库上执行查询并构建另一个 query/queries 成为 运行:

$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

在脚本的末尾,我正在打印必须执行的查询,但不幸的是,变量 $sqlOutputToRun 仅包含大约 3/4 的预期输出。 我想输出会因为大小而被削减,但我不确定如何扩展它。

你知道少了什么吗?

如果你不能没有光标,为什么你不能做这样的事情?

$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

并且一旦您将 print 语句转储为结果集,您也可以转储游标,并且只是 运行 一个简单的查询,例如:

    select 'SELECT TOP (1) * FROM '+ quotename(table_catalog) + '.' + quotename(table_schema) + '.' + quotename(table_name)
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE='BASE TABLE' 
    AND TABLE_NAME LIKE 'x%'

因此在 Powershell 中:

$sql = @"
        select 'SELECT TOP (1) * FROM '+ quotename(table_catalog) + '.' + quotename(table_schema) + '.' + quotename(table_name)
        FROM INFORMATION_SCHEMA.TABLES 
        WHERE TABLE_TYPE='BASE TABLE' 
       -- AND TABLE_NAME LIKE 'x%'
"@

$sqlOutputToRun = $nul

invoke-sqlcmd $sql | foreach { 
     $sqlOutputToRun += $_[0] + "`n"
}

$sqlOutputToRun