Использование PowerShell для перемещения файлов и оставления текстового файла - PullRequest
0 голосов
/ 06 декабря 2018

Если я использую 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 голосов
/ 06 декабря 2018

Если я пойду по названию этого вопроса и предположим, что вы хотите переместить файлы в новое место,
И ваш 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'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...