0
我們有一個客戶端,每小時將一個.pkg文件上傳到我們FTP上的指定文件夾。我想創建一個SQL Server代理作業來獲取該文件,將數據導入到SQL Server數據庫中的表中,然後移動並重命名該文件。如何使用PowerShell從熱文件夾獲取最後一個文件?
我成功的在做這個(用下面的代碼),除了當只有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
我想通了這個問題。每hydropowerdeveloper在http://stackoverflow.com/questions/14714284/count-items-in-a-folder-with-powershell: >好了,事實證明,這是一個怪癖正是造成的,因爲當時只有一個文件在目錄中。一些搜索顯示,在這種情況下,PowerShell返回一個標量對象而不是數組。這個對象沒有count屬性,所以沒有任何東西需要檢索。 所以我只需要用'@'強制一個數組。 – rcurrydev
如果您自己發現瞭解決方案,請將其作爲您自己的答案發布並接受它,以便將您的問題從未答覆的問題隊列中移除。 –