简体   繁体   English

PowerShell Get-Date放入阵列

[英]PowerShell Get-Date into an Array

I'm trying to get three different Timestamps from PowerShell as shown below. 我正在尝试从PowerShell中获取三个不同的时间戳,如下所示。 I've worked out the various commands using GET-DATE to accomplish this but I'm not sure how to make a loop in PowerShell work with GET-DATE and increment GET-DATE with the formatting needed. 我已经使用GET-DATE制定了各种命令来完成此操作,但是我不确定如何在PowerShell中使用GET-DATE进行循环并以所需的格式递增GET-DATE

What I've got so far is below. 到目前为止,我得到的是以下内容。

"1/26/2015 1:00 AM"
"2015-01-26"
"Sunday"
((Get-Date -Format "M/dd/yyyy") + " " + "1:00 am").ToUpper()
(Get-Date -Format "yyyy-MM-dd")
(Get-Date).DayOfWeek
for ($i = 0; $i -lt 7; $i++)
 {
$d = ((Get-Date -Format "M/dd/yyyy").AddDays($i))
$d
 }

So, there's a couple things here... 所以,这里有几件事...

First, you are over complicating things. 首先,您要使事情复杂化。 To see if it is Monday simply do: 要查看是否是星期一,只需执行以下操作:

If((Get-Date).DayOfWeek -eq "Monday"){
    "It is Monday, executing script"
}Else{
    "Not Monday! Abort!"
}

So getting back to what you asked for... an array with the days of the week in it. 因此,返回到您要的...一个包含星期几的数组。 This is where [Enum] comes in real handy. 这是[Enum]派上用场的地方。 You already have used [DayOfWeek] to cast "Monday" as an actual day object not just a string, but you want all of the days from that type. 您已经使用[DayOfWeek]将“星期一”转换为实际的日期对象,而不仅仅是字符串,但是您希望该类型的所有日期都作为。 To do that you can use [Enum] 's getvalues() method as such: 为此,您可以这样使用[Enum]getvalues()方法:

$Days = [Enum]::GetValues([DayOfWeek])

Now, I think I'll try and guess what you were getting at, trying to get the next Monday's date if the script is not run on a Monday. 现在,我想我会尝试猜测您的意思,如果脚本不在周一运行,则尝试获取下周一的日期。 If you want the previous Monday just change the $i++ to $i-- in the following code: 如果要上一个星期一,只需在以下代码中将$i++更改为$i--

If((Get-Date).DayOfWeek -ne "Monday"){
    $i=0
    While((get-date).AddDays($i).DayOfWeek -ne "Monday"){$i++}
    "The next valid day to run this script is $((get-date).AddDays($i).ToShortDateString())."
}Else{
    Do Stuff Here
}

Turns out I was close. 原来我很近。 Here's what clued me in https://stackoverflow.com/a/2249639/4317867 and I apologize for my horrible skills at writing up questions! 这就是在https://stackoverflow.com/a/2249639/4317867中给我的暗示,对于我提出问题的可怕技巧,我深表歉意!

Ended up doing: 最终做了:

for ($i = 1; $i -le 7; $i++)
{
 $d = ((Get-Date).AddDays($i))
 $d2 = $d.ToString("M/dd/yyyy")
 $d2
}

Output is: 输出为:

1/28/2015
1/29/2015
1/30/2015
1/31/2015
2/01/2015
2/02/2015
2/03/2015

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

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