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
 }

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

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"
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.