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

标签 powershell date

我正在编写一个简单的脚本来获取日期,从现在起获取 6 个月后的日期,并将这两个日期复制到剪贴板。运行时,脚本应该复制:Terminated MM/dd/yy - Delete from AD on MM/dd/yyyy但它只是复制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 

最佳答案

失败的原因是因为一旦您使用 -Format "MM/dd/yyyy" 格式化日期它将该变量转换为 string 的类型而不是 datetime这意味着正常 datetime方法不再可用。
出于演示目的,我尽量减少改动。我在下面所做的是设置 $currentDate$futureDate无需将它们隐式转换为字符串。然后,当您连接 $copyThisText 中的字符串时,我会按照您想要的方式对其进行格式化。 .
这会做你想做的。

$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 
此外,有多种格式化字符串的方法可以帮助提高代码的可读性。感谢@Santiago Squarzon 的建议 -
"Terminated {0:MM/dd/yyyy} - Delete from AD on {1:MM/dd/yyyy}" -f $currentDate, $futureDate

关于powershell - 如何在Powershell中使用Get-Date的.AddMonths方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68475698/

相关文章:

javascript - 在 Moment.js 中获取该月第一天的日期名称

powershell - PowerShell强制参数取决于另一个参数

powershell - 使用以 DisplayName 命名的文件夹导入 GPO - Powershell

powershell - 使用Powershell获取当前驱动器号

wpf - Datepicker不允许编辑,也不接受null

Android ThreeTenAbp 获取一年中的所有星期进行排列

java:如何模拟 Calendar.getInstance()?

powershell - 如何将ScriptStackTrace保留在远程计算机上的Invoke-Command中引发的异常中?

arrays - Powershell:引用数组中的单个元素

Javascript getMonth 在添加天数后返回上个月