1

我看到一些奇怪的行为。在我的机器上,PowerShell 返回记录集,我可以遍历记录没有问题。在我同事的机器上(他有权访问我需要从中复制文件的文件共享)正在返回一个记录计数而不是实际记录。我一定错过了一些简单的东西。知道为什么我会看到这种不同的行为吗?

 $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
 $SqlConnection.ConnectionString = "Server = server; Database = db; Integrated Security = True"
 $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
 $SqlCmd.CommandText = "SELECT fileName from SomeTable"
 $SqlCmd.Connection = $SqlConnection
 $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
 $SqlAdapter.SelectCommand = $SqlCmd
 $DataSet = New-Object System.Data.DataSet
 $SqlAdapter.Fill($DataSet)
 $Table = new-object data.datatable
 $Table = $DataSet.tables[0]
 $SqlConnection.Close() 

 function Out-FileForce {
 PARAM($path)
 PROCESS
 {
     if(Test-Path $path)
     {
         Out-File -inputObject $_ -append -filepath $path
     }
     else
     {
         new-item -force -path $path -value $_ -type file
     }
 }
 }

foreach ($Row in $Table.Rows)
{
    $fullPath = $Row.FullFilePathWithName 
    $path = "\\server\folder\"
    $newPath = "C:\newFolder\"


    $newDestination = $fullPath -replace [regex]::Escape($path), $newPath

    #Write-Output $newDestination
    #Write-Output $fullPath

    # recurse should force the creation of the folder structure
    #Copy-Item $fullPath $newDestination -recurse
    Out-FileForce $newDestination
    Copy-Item $fullPath $newDestination -force
    Write-Output $newDestination " done"

}
4

2 回答 2

1

这一行: -

$SqlAdapter.Fill($DataSet)

如果您希望稍后将其分配给某些东西,则返回行数:-

$rowCount = $SqlAdapter.Fill($DataSet)

或者如果您不需要它:-

[无效]$SqlAdapter.Fill($DataSet)

以上都将避免需要跳过 1

希望这可以帮助

于 2013-08-13T07:47:59.557 回答
0

想出了一个解决办法,我仍然不知道为什么。

$DataSetTableRows 导致了这个问题

修复我发布的原始脚本。

将此添加到顶部:

$Table = 新对象 data.datatable $Table = $DataSet.tables[0]

然后在我的循环中我使用了 $Table.Rows

于 2013-04-26T20:36:12.890 回答