Создайте папку по дате, затем переименуйте файл с префиксом предыдущей даты, затем переместите файл по расширению в папку - PullRequest
1 голос
/ 15 марта 2019

Это моя первая публикация, поэтому я прошу прощения, если форматирование неясно или неправильно.Я буду стараться изо всех сил, чтобы все выглядело лучше по ходу работы.
Я пытаюсь создать сценарий Power Shell, который создаст папку с годом и предыдущим месяцем.
Затем я хочу переместить определенный extили файлы только в папку, которая была создана.

Моя проблема сейчас заключается в том, что любой текстовый файл внутри Temp или Temp \ files будет перемещен в создаваемую папку.
Кроме того, файлы, которые были перемещены уже один раз, будут перемещены снова,месяц, и информация в предыдущей папке исчезнет.
Можно ли как-нибудь переместить файлы, находящиеся вне папки, в новую папку?
Теперь я хочу создать еще одну проблему.тот же формат даты, что и в качестве префикса к примеру текстового документа: 201902-_Name.txt

Я не разобрался со второй частью, и я вроде как разобрался с первой частью, за исключением того, что она захватывает что-либо внутри temp иперемещает его в новую папку, которую создает.

# Get the files which should be moved, without folders
$files = Get-ChildItem 'C:\Temp\' -Recurse | where {!$_.PsIsContainer}

# List Files which will be moved
$files

# Target Folder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'C:\Temp\files\'

foreach ($file in $files){
    # Get year and Month of the file
    # I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
    $year = $file.LastWriteTime.Year.ToString()
    $month = (Get-Date).AddMonths(-1).ToString('MM')
    $monthname = (Get-Culture).DateTimeFormat.GetAbbreviatedMonthName($month)

    # Out FileName, year and month
    $file.Name
    $year
    $month
    $monthname

    # Set Directory Path
    $Directory = $targetPath + "\" + $year + $month

    # Create directory if it doesn't exsist
    if (!(Test-Path $Directory)){
        New-Item $directory -type directory
    }

    # Move File to new location
    $file | Move-Item -Destination $Directory
}

1 Ответ

1 голос
/ 15 марта 2019

Самый простой способ решить вашу проблему # 1 - переместить файлы в целевую папку, которая НЕ внутри исходной папки.

Если это не то, что выхотите, тогда вам нужно добавить дополнительный тест для командлета Get-ChildItem, чтобы отфильтровать все файлы, которые находятся в целевой папке.

Примерно так должно работать:

$sourcePath = 'C:\Temp\'        #'# The folder in which the files to move are
$targetPath = 'C:\Temp\files\'  #'# The folder where the files should be moved to

# Get the files which should be moved, without folders and exclude any file that is in the target folder
$files = Get-ChildItem $sourcePath -File -Recurse | Where-Object { $_.FullName -notlike "$targetPath*" }
# for PowerShell version below 3.0 use this:
# $files = Get-ChildItem 'C:\Temp\' -Recurse | Where-Object {!$_.PsIsContainer -and $_.FullName -notlike "$targetPath*"}

# List Files which will be moved
# $files

foreach ($file in $files){
    # Get year and Month of the file
    # I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
    $year      = $file.LastWriteTime.Year
    $month     = (Get-Date).AddMonths(-1).ToString('MM')             # last month from current date
    $monthname = (Get-Culture).DateTimeFormat.GetAbbreviatedMonthName($month)

    # Out FileName, year and month
    # $file.Name
    # $year
    # $month
    # $monthname

    $dateString = '{0}{1}' -f $year, $month
    # Set Directory Path
    $Directory = Join-Path -Path $targetPath -ChildPath $dateString

    # Create directory if it doesn't exsist
    if (!(Test-Path $Directory -PathType Container)){
        New-Item $Directory -ItemType Directory | Out-Null
    }

    # Move File to new location and prepend the date prefix to its name
    $targetFile = Join-Path -Path $Directory -ChildPath ('{0}-{1}' -f $dateString, $file.Name)
    $file | Move-Item -Destination $targetFile -Force
}

Какс помощью той же переменной $ dateString командлет Move-Item не только перемещает, но и переименовывает файлы.

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

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