PowerShell для копирования файлов и добавления Folderame к скопированным файлам - PullRequest
0 голосов
/ 11 марта 2020

Я пытаюсь скопировать файл "ab c .txt" из ежедневной папки в папке root. скажем, пути и файлы исходных папок выглядят так: *

\\Server01\rootdir->01-01-20->abc.txt
\\Server01\rootdir->01-01-20->abc.txt
\\Server01\rootdir->01-01-20->Details->abc.txt
..
..
\\Server01\rootdir->10-25-20->Details->abc.txt
\\Server01\rootdir->11-15-20->abc.txt
\\Server01\rootdir->12-30-20->abc.txt           ---File existed in parent folder
\\Server01\rootdir->12-31-20->Details->abc.txt  ---File not in parent but in child

Я хочу скопировать файлы ab c .txt из всех этих папок в одно место. но во время копирования мне нужно добавить имя папки в файл, как abc_01-01-20.txt. Но есть вероятность, что внутри root -> 01-01-20 может содержаться дочерняя папка ( Details ), и она может иметь такое же имя файла внутри. поэтому, если файл не существует в папке 01-01-20, есть вероятность, что он может существовать в папке " Details ". Если в Родительская папка существовал файл "ab c .txt", сценарий не должен заглядывать в дочернюю ( Подробности ) папку.

TargetDir->abc_01-01-20.txt
TargetDir->abc_01-02-20.txt
..
..
TargetDir->abc_12-31-20.txt

Вот сценарий Я построил

$Source = "\\Server01\root"
$SrcFile="abc.txt"
$GetSrcFile = Get-ChildItem $Source | Where-Object {$_.name -like "$SrcFile"}
$Destination = "C:\Target"
Copy-Item "$Source\$GetFile" "$Destination" -Force -
Confirm:$False -ErrorAction silentlyContinue
if(-not $?) {write-warning "Copy Failed"}
else {write-host "Successfully moved $Source\$SrcFile to $Destination"}

Проблема в том, что этот скрипт не может вытащить и добавить имя папки в файл.

Ответы [ 2 ]

0 голосов
/ 11 марта 2020

Я думаю, вы несколько путаете источник и назначение. Для этого вам нужно получить файлы abc.txt рекурсивно, и только если имя прямой родительской папки похоже на дату, скопируйте файл с новым именем:

$Source      = 'C:\Source\rootdir'       # rootfolder where the subfolders with files are
$Destination = "\\Server01\Destination"  # path to where the files need to be copied

if (!(Test-Path -Path $Destination -PathType Container)) {
    $null = New-Item -Path $Destination -ItemType Directory
}

Get-ChildItem -Path $Source -Recurse -Filter 'abc.txt' -File | 
    Where-Object {$_.DirectoryName -match '\\\d{2}-\d{2}-\d{2}$'} | 
    ForEach-Object {
        $newName = '{0}_{1}{2}' -f $_.BaseName, ($_.DirectoryName -split '\\')[-1], $_.Extension
        $target  = Join-Path -Path $Destination -ChildPath $newName
        try {
            $_ | Copy-Item -Destination $target -Force -Confirm:$false -ErrorAction Stop
            Write-Host "File '$($_.Name)' copied to '$target'"
        }
        catch {
            Write-Warning "Error: $($_.Exception.Message)"
        }
    }
0 голосов
/ 11 марта 2020

Я не проверял это, но я думаю, что есть несколько проблем с вашим кодом. Вы, кажется, смешиваете источник и место назначения. Кроме того, вы собираете файлы в переменную $ ScrFile, но не выполняете итерацию по ней таким образом, чтобы вы могли определить новое имя ...

Я работал над этим очень быстро и не сделал протестируйте его, но как пример того, как вы могли бы sh это сделать, это может быть отправной точкой.

$Source      = "\\Server01\Destination"
$SrcFile     = "abc.txt"
$Destination = "C:\Source\rootdir"

# Note: this can be done with other ForEach permutations as well.

Get-ChildItem $Source -File | 
Where-Object{ $_.Name -match $SrcFile } |
ForEach-Object{
    # Get the name of the dir you found the file in:
    $ParentDirectory = Split-Path $_.DirectoryName -Leaf 

    #calculate a new file name including the directory it was found in:
    $NewFileName     = + $_.BaseName + $ParentDirectory + $_.Extension

    #Join the new name with the directory path you want top copy the file to
    $NewFileName     = Join-Path $Destination $NewFileName 

    # Finally try and copy the file.  Use try catch for more robust error handling
    Try{
        Copy-Item $_.FullName $NewFileName -ErrorAction Stop
        Write-Host -ForegroundColor Green "Successfully copied the file..."
    }
    Catch{
        # You can do a better job here...
        Write-Host -ForegroundColor Red "There was an error copying the file!"
    }
}

Дайте мне знать, если это полезно. Спасибо.

...