Powershell Не удается переместить только файлы из одного каталога в другой? - PullRequest
0 голосов
/ 12 октября 2019

Я пытаюсь переместить только файлы (старые среди всех) из одного source_dir в другой archiv_dir. Source_dir содержит одну дочернюю папку, которую я хочу сохранить там сам и хочу перемещать только файлы.

Я фильтрую последние файлы и перемещаю старые в архив. Ниже приведена структура папки и код

#Source Dir

Log_Sub1  #child dir

Log1.log
Log2.log
Log3.log
Log4.log
Log5.log

powershell

function Keep_Logs_And_Move_Files([int]$No_files_to_keep)
    {
        Write-Host "Count of keep files: " $No_files_to_keep
        # Check and create Archive dir if not exist

        Write-Host "Count of keep files: " $No_files_to_keep
        # Check and create Archive dir if not exist
        $source_dir="D:\Log_Test_Direcotories\Log2"
        $archiv_dir="D:\Log_Test_Direcotories\Log2_archiv"
        $count_of_Files= Get-ChildItem $source_dir | Measure-Object | Select-Object Count
        $existing_files= ls $source_dir

        IF ($count_of_Files.Count -gt $No_files_to_keep){

            # Get the number of latest files
            $files_to_keep=Get-ChildItem -Path $source_dir | Where-Object { -not $_.PsIsContainer } | Sort-Object LastWriteTime -Descending | Select-Object -first $No_files_to_keep

            #compare exsting all files with files_to_keep to get  excluded_files that need to be moved out
            $exclude_files=Compare-Object -ReferenceObject ($files_to_keep | Sort-Object ) -DifferenceObject ($existing_files | Sort-Object)

            #Filter for oly files not directory
            #$Filtered_files=gci -af $exclude_files

            #Write-Host "Filtered files $Filtered_files"

            #Move exclude_files to archive
            foreach($i in $exclude_files){
                Write-Host "Moving file $i..." 
                $i.InputObject | Move-Item -Destination $archiv_dir
            }

        } else{
            Write-Host "OK! Existing files are equal/lesser to the number required latest files!"

        }
    }

#Calling function
Keep_Logs_And_Move_Files 3

Ожидается:

Должны быть перемещены только отфильтрованные (старые) файлыв архив реж. Здесь я храню 3 последних файла, и дочерний каталог должен оставаться в том же исходном каталоге

Actual:

Child-dir (Log_Sub1), также перемещающийся в архивный каталог вместе сстарые файлы.

Может кто-нибудь помочь с этим?

1 Ответ

1 голос
/ 12 октября 2019

Хотя я не совсем уверен, что вы хотите делать с файлами внутри подкаталога, я THINK вы просто хотите оставить этот каталог нетронутым в исходном каталоге.

Вэта функция ниже должна работать для вас. Я изменил его название, чтобы оно соответствовало Verb-Noun соглашению об именах в PowerShell.

function Move-LogFiles {
    [CmdletBinding()]
    Param(
        [ValidateScript({Test-Path -Path $_ -PathType Container})]
        [string]$Source        = "D:\Log_Test_Directories\Log2", 
        [string]$Destination   = "D:\Log_Test_Directories\Log2_archiv",
        [int]$FilesToKeep      = 3
    )
    Write-Verbose "Count of keep files: $FilesToKeep"

    # Check and create Archive dir if not exist
    if (!(Test-Path -Path $Destination -PathType Container)) {
        New-Item -Path $Destination -ItemType Directory | Out-Null
    }

    $files= Get-ChildItem -Path $Source -Filter '*.log' -File | Sort-Object LastWriteTime -Descending

    if ($files.Count -gt $FilesToKeep) {
        for ($i = $FilesToKeep; $i -lt $files.Count; $i++) {
            Write-Verbose "Moving file $($files[$i].Name) to '$Destination'"
            $files[$i] | Move-Item -Destination $Destination -Force
        }
    } 
    else {
        Write-Verbose "OK! Existing files are equal/lesser to the number required latest files!"

    }
}

#Calling function
Move-LogFiles -FilesToKeep 3 -Verbose

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...