我有一个用于维护窗口的功能。我试图找出我做的方式,实际上是最好的方法。
我以格式“2015-05-07 01:00 + 13:00”传递日期,并希望将其与运行日期进行比较。即今天为此目的的日期。 传入的日期将传入一个变量,为了测试我只需手动输入它。因此,HelpMessage。
到目前为止,我认为有效,我相信有更有效的方式来运行我想要的东西。
代码如下:
Function Get-MaintenanceWindow {
PARAM (
[cmdletbinding()]
[Parameter(Position=1,
Mandatory=$True,
HelpMessage="Enter maintenance window to compare against i.e 2015-05-07 01:00+13:00")]
$Window
)
# Pass in two var and compare against, if $window1 < $Window2 still in Window
Write-Host ""
Write-Host " * * * Running Function Maintenance Window * * * "
#Compares two dates
$TodaysDate = (Get-Date)
$xTodaysDate = (Get-Date -Format yyyyMMddhhmm $TodaysDate)
$xWindow = (Get-Date -Format yyyyMMddhhmm $Window)
Write-Host "Today's date is : $xTodaysDate, compared to date is : $xWindow"
Write-Host "Comparing against today's date $xTodaysDate against passed date $Window..."
If ($xTodaysDate -lt $xWindow) {
Write-host $xTodaysDate " is less than `$xWindow $xWindow, still in Maintenance Window!"
$global:Check = $True
}
Else {
Write-Host "Not in Maintenance Window, exiting..."
#$Y = (Get-Date) + " is less than `$Window $Window, still in Maintenance Window!"
$global:Check = $False
Break #Exits Function
}
}
答案 0 :(得分:0)
是的,有一种(方式)更简单的方法可以做到这一点。 PowerShell(即.NET)对日期非常酷。
$TodaysDate = [DateTime]::Now
$xWindow = [DateTime] $Window
它会自动为您解析日期,并且效果非常好。请参阅以下示例:
$date = [DateTime] "5:00 PM"
$date = [DateTime] "Mon, Jan 5, 2014"
$date = [DateTime] "May 4"