使用PowerShell移动文件并保留文本文件

时间:2018-12-05 22:39:12

标签: powershell

如果我使用PowerShell在驱动器中搜索文件夹,以将它们从CSV移动到另一个文件夹。我在如何保留要在替换文件夹中移动的文件夹的文本文件方面空白。

当前用于查找文件夹并移动的PowerShell代码:

$File = Import-Csv C:\share\test\files.txt
foreach ($fileName in $File.FileName) {
    Move-Item -Path "C:\share\test\OldLocation\$fileName" -Destination "C:\share\test\NewLocation\$fileName"
}

1 个答案:

答案 0 :(得分:1)

如果我按此问题的标题回答,并假设您要将文件移到新位置,
AND ,您的CSV如下所示:

FileName
file1.docx
file2.docx
file3.docx
image1.jpg

这应该做到:

$oldLocation = 'C:\share\test\OldLocation'
$newLocation = 'C:\share\test\NewLocation'
# this is the path and filename for the text to leave behind
$movedFiles  = Join-Path -Path $oldLocation -ChildPath 'Files Moved.txt'

$messages    = @()
$filesToMove = Import-Csv 'C:\share\test\files.txt'
foreach ($file in $filesToMove.FileName) {
    $oldFile = Join-Path -Path $oldLocation -ChildPath $file
    $newFile = Join-Path -Path $newLocation -ChildPath $file

    if (Test-Path -Path $oldFile -PathType Leaf) {
        ################################################################################################
        # WARNING: Using parameter '-Force' will overwrite any file in the new location with that name. 
        # If that is not what you want, what will be your strategy ?
        ################################################################################################

        Move-Item -Path $oldFile -Destination $newFile    # -Force
        # add a new line for the text file
        $messages += "File '$file' has been moved to '$newLocation'"
    }
}
if ($messages.Count) {
    # write the textfile with all the files that have been moved in the old location
    Add-Content -Path $movedFiles -Value ($messages -join [Environment]::NewLine)
}
else {
    Write-Warning "No files have been moved."
}

文件移动后,旧位置应包含一个文本文件

File 'file1.docx' has been moved to 'C:\share\test\NewLocation'
File 'file2.docx' has been moved to 'C:\share\test\NewLocation'
File 'file3.docx' has been moved to 'C:\share\test\NewLocation'
File 'image1.jpg' has been moved to 'C:\share\test\NewLocation'