【问题标题】:How do I create a folder and subfolder keeping track of current year如何创建文件夹和子文件夹来跟踪当前年份
【发布时间】:2019-01-14 21:42:31
【问题描述】:

下面的代码让我大吃一惊……我在这里要做的是日期检查……如果当前日期不存在(它是 2020 并且没有 2020 文件夹),那么创建一个 2020 文件夹。否则,如果是2019,没有2020文件夹,就创建一个2020文件夹。

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

这就是我所拥有的……但我的思绪变得杂乱无章,试图保持一切正常。我很确定这是我的逻辑可能混乱的第二个 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
}

【问题讨论】:

    标签: powershell powershell-2.0 powershell-3.0 powershell-4.0


    【解决方案1】:

    我认为$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
    

    【讨论】:

    • (Get-Date).Year + 1
    • 谢谢你们。我刚开始工作。我感谢你们俩的帮助。 =)
    • 如果我要理解 Ansgar 的建议..这个修复就是这个..(实际上,由于 cmets 中的格式,我将编辑我的主要帖子,如果我理解正确,请告诉我.
    猜你喜欢
    • 2013-08-21
    • 1970-01-01
    • 2021-11-03
    • 2014-01-17
    • 2020-07-18
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多