1
Get-ChildItem ".\Stored Procedures\*.sql" | ForEach-Object { sqlcmd -S ServerName -d     DatabaseName -E -i $_.FullName }

When I run a batch of scripts from a folder with the above command, if a problem persists in the intermediate script (like create/Alter/DROP DML script in between) then it should stop there only and need to give me an error message.

0

1 Answer 1

1

You'll need to do a few things:

  1. Set ErrorActionPreference to stop
  2. Use the -b parameter with sqlcmd.exe utility
  3. Capture and log or display output of sqlcmd.exe utility

I answered a similar a question on another forum and I've re-posted the answer here:

echo "select 'Good 1'" > C:\temp\scripts\1.sql
echo "select * from missingTable" > C:\temp\scripts\2.sql
echo "Select 'Good 3'" > C:\temp\scripts\3.sql

$ErrorActionPreference = "Stop"

ForEach ($S In Gci -Path "C:\Temp\Scripts\" -Filter *.sql | Sort-Object Name) {
    try { 
        $result = SqlCmd -b -S $env:computername\sql1 -i $S.FullName
        $result = $result -join "`n"

        if ($LASTEXITCODE -ne 0) {
            throw "$S.FullName : $lastexitcode : $result"
        }
        else {
            write-output "Success: $($s.fullname) : $result" | Out-File C:\Temp\Scripts\sqllogging.txt -Append
        }
    }
    catch {
        write-output "Failed: $_ " | Out-File C:\Temp\Scripts\sqllogging.txt -Append
        throw
    } 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.