1

I am totally new to Powershell. I feel as though I have exhausted looking on the internet, but I also know that this answer should be easy.

I want a loop to:

  1. Run 50 SQL files
  2. Save them as a custom named txt file

For example, if SQL Files are:

  1. E:\SQLscripts\apples.sql
  2. E:\SQLscripts\bananas.sql
  3. E:\SQLscripts\clementines.sql
  4. E:\SQLscripts\oranges.sql
  5. E:\SQLscripts\watermelons.sql
  6. etc.

I want to have:

  1. E:\OutputTXT\apples.txt
  2. E:\OutputTXT\bananas.txt
  3. E:\OutputTXT\clementines.txt
  4. E:\OutputTXT\oranges.txt
  5. E:\OutputTXT\watermelons.txt
  6. etc.

Rather than posting 10 different chunks of code, I have tried the following

  • Export-CSV -NoTypeInformation
  • Export-CSV -NoTypeInformation -Force
  • Export-CSV -NoTypeInformation -Force -
  • Out-File $outdir.$filename.basename.txt
  • Out-File %filename.basename.txt%
  • Out-File ($filename.Basename + ".txt")
  • Path ($outdir + $filename.Name + ".csv")
    $sqlserver = 'local'
    $sqldb = 'dbname'
    $sqluser = 'user'
    $sqlpw = 'pw'
    $sourcedir = 'E:\SQLscripts'
    $outdir = 'E:\OutputTXT'


    foreach ($filename in get-childitem -Path $sourcedir -Filter "*.sql") {
    invoke-sqlcmd –ServerInstance $sqlserver -Database $sqldb -Username $sqluser -Password           
    $sqlpw -InputFile $filename.fullname |
    (missing piece here)
    }
Leigh
  • 11
  • 3
  • What is your question? How to write output from a command to a file? – Mathias R. Jessen Mar 23 '21 at 20:49
  • I want to:1. run all sql files 2. save the query results to a txt file with the same corresponding basename of the sql file. For example, if have sqlfile1.sql I want it to output to sqlfile1.txt. Since I have 30 sql files, though, I want to do this in a looped and automated way. Hope that helps clarify! – Leigh Mar 24 '21 at 17:45

0 Answers0