如何创建跟踪当年的文件夹和子文件夹

How do I create a folder and subfolder keeping track of current year

下面的代码让我感到困惑...我想在这里做的是日期检查...如果当前日期不存在(它是 2020 年并且没有 2020 文件夹)然后创建一个 2020文件夹。否则,如果是2019年,没有2020年的文件夹,就新建一个2020年的文件夹。

第二步...进入文件夹..现在是 2020 年,没有 2020 - 1 月文件夹...然后将去年的 12 - 12 月复制到 2020\ 01 - 1 月文件夹...如果是 2019 年并且没有2020 - January 文件夹,然后将今年的12 - December 复制到2020 - January 文件夹中。

这就是我所拥有的...但我的思绪变得混乱,试图保持一切正常。我很确定这是第二个 if 语句,我的逻辑可能会混乱。

我也不知道没有新的一年如何测试这个。 =)

# Edited to reflect code fix as I understand it.
$arubaBuildsRootPath = "***"
$oldMonth = "12 - December"
#$year = Get-Date -UFormat "%Y"
$year = (Get-Date).year
$newMonth = "01 - January"
$newYear = $year + 1
$oldYear = $year - 1

if( -Not (Test-Path -Path $arubaBuildsRootPath$year ) )
{
    New-Item -ItemType directory -Path $arubaBuildsRootPath$year
}
Else 
{
    New-Item -ItemType directory -Path $arubaBuildsRootPath$newYear
}

if( -Not (Test-Path -Path $arubaBuildsRootPath$year$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
}

我认为 $year + 1 代码没有按您预期的方式工作...PowerShell 将您的 $year 变量视为字符串,因此 + 改为连接 1 .

从本地测试看:

$ (get-date -UFormat '%Y')
2019

$ (get-date -UFormat '%Y')+1
20191

$ ([int](get-date -UFormat '%Y'))+1
2020

所以,我认为如果将 $year 变量设为 int,它应该会按预期工作。

更好(根据@AnsgarWiechers 评论),只需使用当前日期的 Year 属性。那时不需要特殊的格式功能。这也包含了 PowerShell 面向对象的特性。

(Get-Date).Year + 1