根据两列中的CSV值移动文件

时间:2011-09-15 09:11:04

标签: file powershell csv directory move

我一直在编写一个脚本,它将目录中的文件移动到子目录,如果列'folder'包含'Y',则会创建该子目录。在相应文件夹列中没有“Y”的文件将被移动到带有Y的最先前文件名的文件夹中。

我似乎对move-item cmdlet有一些问题。这已经影响了我在另一个脚本中的重命名项目我尝试所以我认为它与我如何尝试访问文件夹中现有文件的文件名有关。

$sourceDir = read-host "Please enter source Dir:"

$csv = import-csv C:\scripts\files\files.csv
$csv | where {$_.folder -eq 'Y'} | % {

        $path = $sourceDir + "\" + $_.fileName
        if(-not $_.PSIsContainer)
        {
            md $path
        }#end if
    }#end for

$move = ".\" + $csv[0].fileName 
$csv | % {
            if ($_.folder -eq 'Y')
            {
                $move = ".\" + $_.fileName
                mi $_.fileName "$move"
            }
            mi $_.fileName "$move"
        } #end for

mi再次出现错误。第一个for循环正确创建文件夹,但第二个文件落下。我正在摆弄它,我能够移动相应的文件。

很抱歉,在我遇到移动问题后,这是该脚本的旧版本。

Move-Item : Cannot find path 'C:\scripts\BB.026.001.001.0017' because it does not exist.
At C:\scripts\Y2.ps1:25 char:7
+                 mi  <<<< $_.fileName "$move"
Move-Item : Cannot find path 'C:\scripts\BB.026.001.001.0017' because it does not exist.
At C:\scripts\Y2.ps1:27 char:6
+             mi  <<<< $_.fileName "$move"
Move-Item : Cannot find path 'C:\scripts\BB.026.001.001.0018' because it does not exist.
At C:\scripts\Y2.ps1:27 char:6
+             mi  <<<< $_.fileName "$move

需要引用文件的扩展名和正确的路径 谢谢,

克雷格。

1 个答案:

答案 0 :(得分:0)

好的,我不确定你的文件扩展名存储在哪里,但是我已经重写了你的脚本,将所有内容放入一个带有IF语句的foreach循环中,以枚举是否应该创建一个文件夹。

$sourceDir = "C:\Temp\sotemp\Source\"                                #Configure source file directory
$destDir = "C:\Temp\sotemp\Dest\"                                    #Configure destination file directory
$csv = import-csv 'C:\Temp\sotemp\files.csv'                         #Import CSV file

$csv | % {                                                           #For each line in the CSV
            $sourceFile = $sourceDir + $_.fileName + ".txt"
            if($_.folder -eq 'Y'){                                   #If the csv entry has a Y in the folder column
                $destPath = $destDir + $_.fileName                   #Build the destination directory path
                if (!(Test-Path -path $destPath)){                   #If the destination directory doesn't exist...
                    New-Item $destPath -itemtype directory -force    #Force creation of the destination directory if it doesn't exist
                }
                mi $sourceFile $destPath                             #Move the file!
            }
            else {
                $destPath = $destPath                                #This isn't needed, but it explicitly shows we are reusing the $destPath variable with whatever was in it the last time we populated it
                mi $sourceFile $destPath                             #Move the file!
            }
        }

让我知道如果我离开目标,如果我在目标上,你只需要更新路径和文件扩展名。此外,没有错误检查,我没有在文件移动中使用'-force'参数来强制覆盖。该脚本还依赖于CSV中第一行的文件夹列中的“Y”,以确保填充$ destPath变量。

相关问题