【问题标题】:How to solve the issue of variables not picking up the create date time of the files?如何解决变量没有获取文件的创建日期时间的问题?
【发布时间】:2022-06-10 20:35:42
【问题描述】:

如果我犯了业余错误,我深表歉意,因为我对 PowerShell 还很陌生。

最近,我的任务是构建一个 PowerShell 脚本,以根据年份(例如 2022 年)和日期范围(例如 220601 - 220610)将自动生成的文件归档到文件夹中。由于源文件夹本身有很多文件,我决定使用 foreach 循环遍历每个单独的文件,注意它们的创建日期时间也可能不同。

$FileCreationTime = $file.CreationTime
$YearMonthDate = $FileCreationTime.ToString("yyMMdd")
$MonthDate = $FileCreationTime.ToString("MMdd")
$YearMonth = $FileCreationTime.ToString("yyMM")
$Year = $file.CreationTime.ToString("yyyy")
$Month = $FileCreationTime.ToString("MM")
$Day = $FileCreationTime.ToString("dd")

$files = Get-ChildItem “C:\Test Folder\*.xml”

foreach($file in $files)
{...}

但是,此方法将变量$FileCreationTime 改为文件夹(测试文件夹)的创建日期时间。有没有办法解决这个问题?提前感谢您的任何回复。

【问题讨论】:

  • 您是否认为foreach 循环围绕所有定义,例如$MonthDate$YearMonth 等将为每个文件更新?如果是这样,定义需要在循环中才能起作用。

标签: powershell


【解决方案1】:

$file 未在代码示例的开头定义。变量分配不会按文件更新,除非您将它们移到循环主体内

$files = Get-ChildItem “C:\Test Folder\*.xml”

foreach($file in $files)
{
    $FileCreationTime = $file.CreationTime
    $YearMonthDate = $FileCreationTime.ToString("yyMMdd")
    $MonthDate = $FileCreationTime.ToString("MMdd")
    $YearMonth = $FileCreationTime.ToString("yyMM")
    $Year = $file.CreationTime.ToString("yyyy")
    $Month = $FileCreationTime.ToString("MM")
    $Day = $FileCreationTime.ToString("dd")

    # Now move the file into a folder based on e. g. $Year
}

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 2017-12-16
    • 2010-09-19
    • 2021-07-14
    • 2013-01-28
    相关资源
    最近更新 更多