private/Get-ProcessOutput.ps1

function Get-ProcessOutput
{
    Param (
                [Parameter(Mandatory=$true)]$FileName,
                $Args
    )
    
    $process = New-Object System.Diagnostics.Process
    $process.StartInfo.UseShellExecute = $false
    $process.StartInfo.RedirectStandardOutput = $true
    $process.StartInfo.RedirectStandardError = $true
    $process.StartInfo.FileName = $FileName
    $process.StartInfo.CreateNoWindow = $true
    if($Args) { $process.StartInfo.Arguments = $Args }
    
    $process.Start() | Out-Null

    while (-not $process.WaitForExit(100))
    {
        while (-not $process.StandardOutput.EndOfStream)
        {
            $stdout = $process.StandardOutput.ReadLine()
            Write-Host $stdout -ForegroundColor Green
        }
    }
Write-Host "Process has completed" -ForegroundColor Green
        
    if (-not $process.StandardOutput.EndOfStream)
    {
        $stdout = $process.StandardOutput.ReadToEnd()
        Write-Host $stdout -ForegroundColor Green
    }
    
    if (-not $process.StandardError.EndOfStream)
    {
        $stderr = $process.StandardError.ReadToEnd()
        Write-Host $stderr -ForegroundColor Red
    }
    

}
<#
Clear-Host
$query = @"
DECLARE @counter INT = 1
print 'Print start before any select statements'
RAISERROR('Throw an error to flush messages to output',10,1) WITH NOWAIT -- flush messages
WHILE (@counter < 5)
BEGIN
    if (@counter = 3)
    begin
        select 1/0
    end
        select @counter
        print 'print counter during loop: ' + cast(@counter as varchar)
    RAISERROR('zxczxc',10,1) WITH NOWAIT -- flush messages
     
    WAITFOR DELAY '00:00:01';
 
    SET @counter += 1
end
 
 
select 'loop done'
RAISERROR('',10,1) WITH NOWAIT -- flush messages
 
--WAITFOR DELAY '00:00:05';
 
 
 
"@
 
 
# sqlcmd will output select statements, but print message and errors will not be outputtet before end of execution
#write-host "Executing query using osql.exe"
#Get-ProcessOutput -FileName "osql.exe" -Args "-S localhost -d master -b -E -Q ""$query"" -r1"
 
write-host "Executing query using sqlcmd.exe"
Get-ProcessOutput -FileName "sqlcmd.exe" -Args "-S localhost -d master -b -E -Q ""$query"" -r1"
#Get-ProcessOutput -FileName "cmd.exe" -Args "/c ping localhost"
 
#>