Как я могу настроить scipt для определения года и создания папки для нового года? - PullRequest
0 голосов
/ 30 апреля 2019

Я написал код, который в основном занимает последний месяц, копирует его, переименовывает в следующий месяц и удаляет все файлы, сохраняя структуру папок.Этот код работает.На январь я пытался стать модным и потерпел неудачу.Что я пытаюсь сделать в январе, так это настроить проверку ... это новый год?Если нет: посмотрите на текущий год и создайте новую папку с новым годом, скопируйте декабрь текущего года в папку нового года и продолжите работу с моим рабочим сценарием.Если да: создайте папку с новым годом, скопируйте декабрь с прошлого года и продолжите работу с рабочим сценарием.

-----
$arubaBuildsRootPath = "***"
$oldMonth = "12 - December"
$year = (Get-Date).year
$newMonth = "01 - January"
$newYear = $year + 1
$oldYear = $year - 1
#Create a variable $correctYear so the $correctYear variable always shows the new year date as defined in the if statement above correctly
if( -Not (Test-Path -Path $arubaBuildsRootPath\$year ) )
{
    $correctYear = (Get-Date).year
}
Else 
{
    $correctYear = (Get-Date).year + 1
}

#Determine if it is the old year or the new year at time scipt is run
if( -Not (Test-Path -Path $arubaBuildsRootPath\$year ) )
{
    New-Item -ItemType directory -Path $arubaBuildsRootPath\$year
}
Else 
{
    New-Item -ItemType directory -Path $arubaBuildsRootPath\$newYear
}


#$dir = '$arubaBuildsRootPath\2019'
#
#$year = (Get-Date).Year
#if ("$year" -eq (Split-Path $dir -Leaf)) {
    # do something
#} else {
#    $parent = Split-Path $dir -Parent
#    $newdir = Join-Path $parent ($year + 1)
#    New-Item $newdir -Type Directory | Out-Null
#} 
if( -Not (Test-Path -Path $arubaBuildsRootPath\$correctYear\$newMonth ) )
{
    Copy-Item -Path "$arubaBuildsRootPath\$oldYear\$oldMonth\" -Destination "$arubaBuildsRootPath\$newYear\$newMonth" -recurse -Force
}
Else 
{
    Copy-Item -Path "$arubaBuildsRootPath\$year\$oldMonth\" -Destination     "$arubaBuildsRootPath\$newYear\$newMonth" -recurse -Force
}
---
#Copy-Item -Path "$arubaBuildsRootPath\$year\$oldMonth\" -Destination           "$arubaBuildsRootPath\$newYear\$newMonth" -recurse -Force
"Work, work";
Start-Sleep -Second 2;
Get-ChildItem -Path $newMonth -Include *.* -File -Recurse | foreach {     $_.Delete()};
"";
"Job's Done";
Start-Sleep -Second 2;
stop-process -Id $PID

Ответы [ 2 ]

1 голос
/ 30 апреля 2019

Вам лучше объяснить что скопировать с предыдущего месяца.

Учитывая эту старую структуру

> Tree A:\ /F
A:\
└───Test
    └───2019
        └───03 - Mar
            │   bar.txt
            │
            └───foo
                    baz.txt

Этот скрипт:

$arubaBuildsRootPath = 'A:\Test'  
# $arubaBuildsRootPath = "***"

$ThisMonth = Join-Path $arubaBuildsRootPath (Get-Date -f 'yyyy\\MM - MMM')
$PrevMonth = Join-Path $arubaBuildsRootPath (Get-Date).AddMonths(-1).ToString('yyyy\\MM - MMM')

if (!(Test-Path $ThisMonth)){
    New-Item -Path $ThisMonth -ItemType Directory | Out-Null
    Robocopy $PrevMonth $ThisMonth /XJ /E /NOCOPY
}
Tree A:\ /F

Урожайность здесь:

> Tree A:\ /F
A:\
└───Test
    └───2019
        ├───03 - Mar
        │   │   bar.txt
        │   │
        │   └───foo
        │           baz.txt
        │
        └───04 - Apr
            └───foo

Таким образом, только структура папок копируется в текущий месяц.

0 голосов
/ 30 апреля 2019

А как насчет этого?

$curr = Get-Date
$next = $curr.AddMonths(1)

$srce = 'arubaBuildsRootPath\' + $curr.Year + '\' + $curr.Month + '\'
$dest = 'arubaBuildsRootPath\' + $next.Year + '\' + $next.Month


$excl = Get-ChildItem $dest
Copy-Item -Path $srce -Destination $dest -Filter {PSIsContainer} -Exclude $excl -Recurse
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...