gpt4 book ai didi

powershell - PowerShell如何处理一月份的((Get-Date).Month)-1?

转载 作者:行者123 更新时间:2023-12-03 00:58:59 33 4
gpt4 key购买 nike

几个月前,我写了一个Powershell / Robocopy备份脚本。它为备份创建一个文件夹,其中包含进行备份的年份和月份(例如:2019 11)。由于脚本在每个新月的第一个月运行,因此该月必须少一个月。一切进展顺利,但我只是意识到我不太确定该脚本在1月1日前的表现如何。是否有人会煽动1月1日的输出,我是否有办法测试这一点以确认?

$month = (Get-Date -UFormat "%Y") + ' ' + ((((Get-Date).Month) - 1)).ToString()
# When run on November 1st, it creates a folder for the October backups called "2019 10".
# When run on December 1st, it creates a folder for the November backups called "2019 11".

1月1日运行时,它将为12月的备份命名该文件夹吗?它会被称为“2019 12”吗? “2019 00”?有没有一种方法可以让我轻松测试依赖时间的行为,而无需手动调整PC的日历?

最佳答案

Get-Date(可选)接受日期进行操作(通过-Date或按位置),该日期默认为当前时间点。

另外,您可以使用-Day修改目标日期的月份部分(以及类似的-Month-Year);传递-Day 1将返回目标日期所在月份的第一天的日期。

这样就可以确保在生成的日期上调用.AddDays(-1)属于上个月(它返回上个月的最后一天)。
.ToString() System.DateTime 方法允许您使用custom date and time format strings执行数据的自定义字符串格式。

放在一起:

# PRODUCTION USE:
# The reference date - now.
$now = Get-Date

# OVERRIDE FOR TESTING:
# Set $now to an arbitrary date, 1 January 2020 in this case.
# Note: With this syntax, *month comes first*, irrespective or the current culture.
$now = [datetime] '1/1/2020'

# Get the first day of the month of the date in $now,
# subtract 1 day to get the last day of the previous month,
# then use .ToString() to produce the desired format.
(Get-Date $now -Day 1).AddDays(-1).ToString('yyyy MM')

以上 yield :

2019 12

注意: PowerShell强制转换(例如 [datetime] '1/1/2020' )通常使用invariant culture 来确保跨不同文化的行为的稳定性;这种虚拟文化与美式英语文化相关联,并支持其月初日期格式(例如 12/1/2020指的是2020年12月1日,而不是2020年1月12日)。

相反,令人惊讶的是 ,当您将参数传递给cmdlet时,数据转换是对文化敏感的;也就是说,例如在法国文化( fr-FR)中,调用 Get-Date 12/1/2020的结果将在2020年1月12日,而不是2020年12月1日,这是美国英语文化( en-US)返回的结果。

this GitHub issue中讨论了这种行为上的问题差异-行为不太可能更改,但是出于保持向后兼容性的目的。

关于powershell - PowerShell如何处理一月份的((Get-Date).Month)-1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59327602/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com