使用PowerShell的日期之间的月差
我需要有广告用户帐户的到期日期,现在有多少个月,它的剩余日期,直到将被禁用 我尝试下的代码,但我在1个月,我有不到一个月的时间,我想有答案像0个月27天使用PowerShell的日期之间的月差,powershell,date,Powershell,Date,我需要有广告用户帐户的到期日期,现在有多少个月,它的剩余日期,直到将被禁用 我尝试下的代码,但我在1个月,我有不到一个月的时间,我想有答案像0个月27天 $StartDate (DateNow) 2019-08-29 00:00:00 AccountExpirationDate
$StartDate (DateNow)
2019-08-29 00:00:00
AccountExpirationDate
---------------------
2019-09-26 00:00:00
$ExpirDate = Get-ADUser test111 -Properties AccountExpirationDate | select AccountExpirationDate
AccountExpirationDate
---------------------
2019-09-26 00:00:00
$EndDate= $ExpirDate.AccountExpirationDate
2019-09-26 00:00:00
$StartDate = (GET-DATE)
2019-08-29 00:00:00
NEW-TIMESPAN –Start $StartDate –End $EndDate
Days : 27
Hours : 10
Minutes : 29
Seconds : 56
$monthdiff = $EndDate.month - $StartDate.month + (($EndDate.Year - $StartDate.year) * 12)
1
(这里我得到了数字1,但我只有不到一个月的时间)您可以只对日期进行常规算术运算,但如果没有月份,它将返回$null而不是0
$today - date
$ExpirDate = Get-ADUser test111 -Properties AccountExpirationDate | select AccountExpirationDate
$diffday = $today - $expirDate
$diffday.days
$diffday.months
if ($diffday.months -eq $null)
{
$Diffday.months =0
}
我相信这就是你想要的,或者可以相对容易地调整以实现它
$today = Get-Date;
$endOfYearDate = "12/31/$($today.Year)";
$endOfYear = Get-Date($endOfYearDate);
$monthsLeftInTheYear = ($endOfYear.Month - $today.Month);
$daysLeftInTheYear = ($endOfYear - $today);
$daysLefInTheYear.Days;
这是意料之中的,如果你选择2018-12-31和2019-01-01,只比较年份,你也会得到1年的差异
$EndDate.Month
返回的整数不再是日期时间类型。为了澄清,日期之间的数学将返回Timespan
类型。我在$diffday.months中没有得到任何值!应该有价值吗?如在中,周期是否扩展超过一个月?