Изменить структуру папок Год> Месяц на основе имени файла (DATE) -powershell - PullRequest
0 голосов
/ 15 октября 2019

Я пытаюсь создать скрипт, который выполняет следующие действия:

1) Проверьте все подпапки / файлы внутри MASTERFOLDER

2) Все файлы имеют одинаковое расширение, и оно было измененов тот же день

Скрипт для создания папки Monthly и перемещения файлов в нее каждый месяц .

Код основан на вопросе выше:

# Get the files which should be moved, without folders
$files = Get-ChildItem '\\test\d$\Reports\client *' -Recurse | 
where {!$_.PsIsContainer}

# List Files and names which will be moved
$files.names

# Target Folder where files should be moved to. The script will automatically  create a folder for the year and month.
 $targetPath = '\\test\d$\Reports\client\'

foreach ($file in $files)
 {

 # Get year and Month of the file

$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString("00")
$monthname = (Get-Culture).DateTimeFormat.GetAbbreviatedMonthName($month)

LastWriteTime не работает - файлы должны быть отсортированы по имени, содержащему дату, например: ClientReportX 20191014 file1.csv

Возможно, использовать -match для 2015 года - 2019 + месяцев для каждого года

   $filesstructure| foreach-object (file in files) { 
   if($file.name-match '2019') {
 #MOVE TO FOLDER 2019 - >  MONTH OF FILE 
  ELSE($filename -match '2018' {
 #MOVE TO FOLDER 2018 ->  MONTH OF FILE 

.....

Остальной код

# Set Directory Path
$Directory = $targetPath + "\" + $month + $monthname
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
 $file | Move-Item -Destination $Directory
 }

Цель: главная папка> Список подпапок каждого года 2019 - 2015. Внутри каждогоПапка год> Месяц январь - декабрь.

Я ценю любую помощь

1 Ответ

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

Вы можете использовать .Substring () , чтобы получить год, месяц и день из имени файла, показанного ниже. После этого вы можете создать новый объект DateTime и получить имя месяца.

$FileName = 'ClientReportX 20191014 file1.csv'

$Year = $FileName.Split(' ')[1].Substring(0, 4)
$Month = $FileName.Split(' ')[1].Substring(4, 2)
$Day = $FileName.Split(' ')[1].Substring(6, 2)

$MonthName = Get-Date -Year $Year -Month $Month -Day $Day -UFormat '%B'

Надеемся, что дата всегда в том же формате ... В этом примере используется регулярное выражение ( О регулярных выражениях ) и автоматическая переменная $ Matches Hashtable для извлечения захваченного текста.

$FileName = 'ClientReportX 20191013 file1.csv'
if ($FileName -match '([12]\d{3}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01]))') #Check with regex if date is in file name
{
    $DateFromFileName = $Matches[0] #$Matches is a default variable (Hashtable) and the matches will be stored here

    $Year = $DateFromFileName.Substring(0, 4)
    $Month = $DateFromFileName.Substring(4, 2)
    $Day = $DateFromFileName.Substring(6, 2)

    $MonthName = Get-Date -Year $Year -Month $Month -Day $Day -UFormat '%B'

    $MonthName
}

$Matches.Clear() #Clear the match
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...