我正在构建一个脚本,将多个平面文本文件导入SQL Server管理工作室。目前,我可以使用
导入一个文件AutoImportCommaFlatFiles -location "C:\..." -file "test" -extension ".txt" -server "Database" -database "test"
有没有办法从文件夹中导入所有文本文件,例如-file" *"而不是为每个新文件使用上面的代码
我目前的代码是
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""
答案 0 :(得分:1)
只需从Get-ChildItem
管道您想要的文件即可。 FileInfo对象中已经提供了所有必需的字段:
Get-ChildItem C:\...\*.txt | ForEach-Object {
AutoImportCommaFlatFiles -location $_.DirectoryName -file $_.BaseName -extension $_.Extension -server "Database" -database "test"
}