【问题标题】:How do I get the last file from a hot folder using PowerShell? [duplicate]如何使用 PowerShell 从热文件夹中获取最后一个文件? [复制]
【发布时间】:2014-06-27 13:09:45
【问题描述】:

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

我成功地做到了这一点(使用下面的代码),除非只剩下 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

【问题讨论】:

  • 我发现了问题所在。 stackoverflow.com/questions/14714284/… 的每个 hydropowerdeveloper:> 好吧,事实证明这是一个怪癖,正是因为目录中只有一个文件。一些搜索显示,在这种情况下,PowerShell 返回一个标量对象而不是一个数组。该对象没有 count 属性,因此没有任何可检索的内容。所以我只需要使用'@'强制一个数组。
  • 如果您自己发现了解决方案,请将其作为您自己的答案发布并接受,这样您的问题就会从未回答的问题队列中删除。

标签: sql sql-server powershell


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2020-04-10
    相关资源
    最近更新 更多