I have SQL scripts that I run using Invoke-SqlCmd
. At the top of each file, I have a USE
statement. I noticed that after an error occurs, the user is sent back to their default database (usually master
). The problem is that it continues running the script; it just dumps everything under the master schema. Then I have to go through and remove a bunch of tables, views, etc.
Right now I am just relying on -AbortOnError
to quit immediately. However, most of the time, my errors are actually not a big deal. Running the script multiple times would actually resolve the issues, so long as everything ran under the same database. The long-term solution is to fix my SQL scripts, obviously. I was wondering if there was a way to prevent Invoke-SqlCmd
from switching to a different database in the meantime.
Example:
# Use Windows Authentication
Invoke-SqlCmd -InputFile "test.sql"