简体   繁体   English

如何在Powershell中使用Get-Date的.AddMonths方法

[英]How to use the .AddMonths method of Get-Date in Powershell

I am writing a simple script that gets the date, gets the date 6 months from now, and copies both of those dates to the clipboard.我正在编写一个简单的脚本来获取日期,从现在起获取 6 个月后的日期,并将这两个日期复制到剪贴板。 When run, the script is supposed to copy:运行时,脚本应该复制:

Terminated MM/dd/yy - Delete from AD on MM/dd/yyyy
But it only copies但它只是复制
Terminated MM/dd/yyyy - Delete from AD on

$currentDate = Get-Date -Format "MM/dd/yyyy"
$futureDate = Get-Date.AddMonths(6) -Format "MM/dd/yyyy"
$copyThisText = "Terminated " + $currentDate + " - Delete from AD on " + $futureDate
$copyThisText | clip 

The reason it failed is because once you format a date using -Format "MM/dd/yyyy" it converts that variable to a type of string rather than datetime which then means that the normal datetime methods are no longer available.它失败的原因是因为一旦您使用-Format "MM/dd/yyyy"格式化日期,它就会将该变量转换为string类型而不是datetime ,这意味着正常的datetime方法不再可用。

For demonstration purposes I have tried to change as little as possible.出于演示目的,我尽量减少改动。 What I have done below is set the $currentDate and $futureDate without implicitly converting them to strings.我在下面所做的是设置$currentDate$futureDate而不将它们隐式转换为字符串。 I then format them the way you want when you are concatenating the strings in $copyThisText .然后,当您连接$copyThisText的字符串时,我会按照您想要的方式对其进行格式化。

This will do what you want.这会做你想做的。

$currentDate = Get-Date
$futureDate = (Get-Date).AddMonths(6) 
$copyThisText = "Terminated " + $currentDate.tostring("MM/dd/yyyy") + " - Delete from AD on " + $futureDate.tostring("MM/dd/yyyy")
$copyThisText | clip 

Furthermore there are multiple ways to format the strings that could aid in readability of the code.此外,有多种格式化字符串的方法可以帮助提高代码的可读性。 Thanks @Santiago Squarzon for the suggestion -感谢@Santiago Squarzon 的建议 -

"Terminated {0:MM/dd/yyyy} - Delete from AD on {1:MM/dd/yyyy}" -f $currentDate, $futureDate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM