如何使用PowerShell从hot文件夹中获取最后一个文件?

时间:2014-06-27 13:09:45

标签: sql sql-server powershell

我们有一个客户端每小时将一个.pkg文件上传到我们FTP上的指定文件夹。我想创建一个SQL Server代理作业来获取该文件,将数据导入SQL Server数据库中的表,然后移动并重命名该文件。

我成功完成了这项工作(使用下面的代码),除非只剩下1个文件。当只剩下一个文件时,它将不会导入...然后它会移动包含文件的实际文件夹(重命名文件夹)。我还提供了以下错误。

脚本:

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"

错误:

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

1 个答案:

答案 0 :(得分:0)

我弄明白了这个问题。在stackoverflow.com/questions/14714284 / ...上的每个水电开发人员:&gt;好吧,事实证明这是一个怪癖,正是因为目录中只有一个文件。一些搜索显示,在这种情况下,PowerShell返回标量对象而不是数组。此对象没有count属性,因此无需检索任何内容。所以我只需要使用'@'强制数组。

相关问题