I'm building a script to import multiple flat text files to the SQL server management studio. Currently I'm able to import one file using
AutoImportCommaFlatFiles -location "C:\..." -file "test" -extension ".txt" -server "Database" -database "test"
Is there a way to import all text files from a folder like -file "*" instead of using above code for every new file
My current code is
Function AutoImportCommaFlatFiles($location, $file, $extension, $server, $database)
{
$full = $location + $file + $extension
$all = Get-Content $full
$columns = $all[0]
$columns = $columns.Replace(" ","")
$columns = $columns.Replace("|","] VARCHAR(100), [")
$table = "CREATE TABLE " + $file + "([" + $columns + "] VARCHAR(100))"
$connection = New-Object System.Data.SqlClient.SqlConnection
$buildTable = New-Object System.Data.SqlClient.SqlCommand
$insertData = New-Object System.Data.SqlClient.SqlCommand
$connection.ConnectionString = "Data Source=" + $server + ";Database=" + $database + ";integrated security=true"
$buildTable.CommandText = $table
$buildTable.Connection = $connection
## Added to function;
$x = 0
$insertData.CommandText = "EXECUTE stp_CommaBulkInsert @1,@2"
$insertData.Parameters.Add("@1", $full)
$insertData.Parameters.Add("@2", $file)
$insertData.Connection = $connection
$connection.Open()
$buildTable.ExecuteNonQuery()
$connection.Close()
## Added to function
$x = 1
if ($x = 1)
{
$connection.Open()
$insertData.ExecuteNonQuery()
$connection.Close()
}
}
AutoImportCommaFlatFiles -location "C:\..." -file "test" -extension ".txt" -server "Database" -database "test"
AutoImportCommaFlatFiles -location "C:\..." -file "test2" -extension ".txt" -server "Database" -database "test""