1

I am trying to write a powershell script that would create a sql file with a list of file names within a given directory appended by a PRINT statement and ":r" command at the beginning of each filename and finished by "GO" at the end of the filename.

Please see below.

PRINT 'C:/Schemas/Admin.sql'
GO
:r "C:/Schemas/Admin.sql"
GO
PRINT 'C:/Schemas/Audit.sql'
GO
:r "C:/Schemas/Audit.sql"
GO

I am able to print out the file names, but I can't seem to figure out how to prefix and suffix each line. This is what I have:

(get-childitem "C:\schemas" -recurse | where {$_.extension -eq ".sql"}).fullname | out-file "C:\powerShell\masterSQL.sql"

1 Answer 1

2

So if you can make it show in the console the way you want, then you can either capture to a variable or pipe straight out as the same format. A couple of improvements can be made.

First, do the filtering on the Get-ChildItem command itself, letting the filesystem provider to the heavy lifting. Much faster than getting all files and filtering with Where-Object

Second, use Set-Content so you don't end up with weird or otherwise unexpected encoding issues.

Last thing to note is the doubled up double quotes around the $_ (the fullname) this is to ensure the path is surrounded with double quotes.

(Get-ChildItem "C:\schemas" -Filter *.sql -Recurse).FullName |
        ForEach-Object {
            "PRINT ""$_"""
            "GO"
            ":r ""$_"""
            "GO"
        } | Set-Content -Path "C:\powerShell\masterSQL.sql" -Encoding UTF8
     
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.