We have a client that uploads one .pkg file each hour to a specified folder on our FTP. I want to create a SQL Server Agent Job to grab that file, import the data into a table in a SQL Server DB, then move and rename the file.
I am successful in doing this (using the code below) except when there is only 1 file left. When there is only one file left it will not import... and then it moves the actual folder with the file in it (renaming the folder as it does this). I have also provided the errors below.
Script:
Function AutoImportCommaFlatFilesTopOne($location, $server, $database)
{
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = "Data Source=" + $server + ";Database=" + $database + ";integrated security=true"
$files = Get-ChildItem $location
$fileName = $files[0]
$full = $location + $fileName
$table = "rawUSPS"
$insertData = New-Object System.Data.SqlClient.SqlCommand
$insertData.CommandText = "EXECUTE stp_CommaBulkInsert @1,@2"
$insertData.Parameters.Add("@1", $full)
$insertData.Parameters.Add("@2", $table)
$insertData.Connection = $connection
$connection.Open()
$insertData.ExecuteNonQuery()
$connection.Close()
move-item $full (("C:\Test\archiveFolder\{0:yyyyMMdd_HHmmss}" + "_" + $fileName.BaseName + ".log") -f (get-date))
}
AutoImportCommaFlatFilesTopOne -location "C:\Test\testFolder\" -server "LAN-DP-03" -database "FlatFileInsertTestingDB"
The errors:
PS C:\Users\rcurry> C:\Scripts\140627.ps1
Unable to index into an object of type System.IO.FileInfo.
At C:\Scripts\140627.ps1:8 char:24
+ $fileName = $files[ <<<< 0]
+ CategoryInfo : InvalidOperation: (0:Int32) [], RuntimeException
+ FullyQualifiedErrorId : CannotIndex
Exception calling "ExecuteNonQuery" with "0" argument(s): "Cannot bulk load because the file "C:\Test\testFolder\" could not be opened. Operating system error
code 3(The system cannot find the path specified.)."
At C:\Scripts\140627.ps1:21 char:32
+ $insertData.ExecuteNonQuery <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException