Color me confused, as I am having a really hard time trying to get what you are after.
Bare with me, I’m old and halftimers kicks in, well, you know.
You are getting a bunch of files with this…
Get-ChildItem C:\Folder | foreach{$_.Name -replace ".sql",""}
Then passing those file names (dbo.sql1, stg.sql2) sequentially, to this …
foreach{"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= $_ AND TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = '$_' ) BEGIN"}
… what exactly did you expect to happen?
In that second foreach, you are not passing any kind of executable command or statement, just a string with the filename.
Get-ChildItem D:\Temp\*.sql |
foreach{$_.Name -replace ".sql",""}
# Results
dbo1
stg2
Why are you removing both .sql tokens again?
Or did you mean to do this?
# Remove the file extension
Get-ChildItem D:\Temp\*.sql |
foreach{$_.Basename}
# Results
dbo.sql1
stg.sql2
and them pass that adjusted filename to this string?
Get-ChildItem D:\Temp\*.sql |
foreach{$_.Basename} |
foreach{"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= $_ AND TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = '$_' ) BEGIN"}
# Results
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= dbo.sql1 AND TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'dbo.sql1' ) BEGIN
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= stg.sql2 AND TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'stg.sql2' ) BEGIN
The above is just passing a string without calling SQL to run it. Is that what you meant to do?
Then pass those to some other file to run as a SQL command, using either Out-File or redirects?
I am working under the assumption that these are different SQL instances, as per the .sql1 and .sql2