0

I'm trying to get three different Timestamps from PowerShell as shown below. 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.

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
 }
user4317867
  • 2,397
  • 4
  • 31
  • 57

2 Answers2

1

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. 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. To do that you can use [Enum]'s getvalues() method as such:

$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:

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
}
TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56
  • Thank you @TheMadTechnician, the IF statement is much better. Now, for the script goal: I'm writing a script to automate creating tickets. The script is run on Monday and needs to create three variables in various formats. For example `My-Ticket -date "1/26/2015 1:00 AM" -day "2015-01-26" -dayofweek "Monday"` – user4317867 Jan 28 '15 at 03:04
0

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!

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
Community
  • 1
  • 1
user4317867
  • 2,397
  • 4
  • 31
  • 57