Add to Technorati Favorites
Welcome to ThePowerShellGuy.com Sign in | Join | Help

Hey, PowerShell Guy ! How Can I Tell If a Script is Running on the First or Second Monday of a Month?

Scripting games are over, but if you want some more PowerShell execersises , the rest of the scriptcenter including VbScript content might be usefull also.

As you might know, I also like to translate Hey Scripting Guy questions to PowerShell

(For a list of former Hey Scripting Guy translations on this blog and my old one and a list of links my ScriptingGames 2006 PowerShell answers see this post : Scripting Games MMVII PowerShell Competition )

Yesterday I translated another Hey Scripting Guy column answer to PowerShell

How Can I Tell If a Script is Running on the First or Second Monday of a Month?

 

The PowerShell version I made looks like this

 

$date = get-date

$Mondays = 1..7 | 
    Where {
        ([datetime]$date.tostring("MM/$_/yyyy")).dayOfWeek -eq 'Monday'
    } | 
    Foreach {
        $date.tostring("MM/$_/yyyy")
        $date.tostring("MM/$($_ +7)/yyyy")
    }

if ($Mondays -contains $date.tostring("MM/dd/yyyy")) {
    "Carry out the task."
} Else {
    "Don't carry out the task."
}

 

 

*Tip* Try translating some of the Hey Scripting Guy answers to PowerShell yourself (and better yet post your solutions also)

I think it's good training and lots of fun ;-)

 

Enjoy,

Greetings /\/\o\/\/

Published Friday, February 23, 2007 1:24 PM by admin
Filed under: , ,

Comments

# re: Hey, PowerShell Guy ! How Can I Tell If a Script is Running on the First or Second Monday of a Month?

Wouldn't checking if today is a monday and the day is less than 14 (14 could never be a third monday, and it's the very last day a second monday could occur) be more efficient?

But that's probably something to bother the scripting guys with instead of you :P

Tuesday, February 27, 2007 9:01 AM by Erik Renes

# re: Hey, PowerShell Guy ! How Can I Tell If a Script is Running on the First or Second Monday of a Month?

@ Erik

Yes,

the oneliner would be (for second day ) :

if ((8..14) -contains $date.Day -and $date.DayOfWeek -eq 'Monday') {"Do Task"}

PoSH> $date = get-date

PoSH> if ((8..14) -contains $date.Day -and $date.DayOfWeek -eq 'Monday') {"Do Task"}

PoSH> $date = [datetime]'02/12/2007'

PoSH> if ((8..14) -contains $date.Day -and $date.DayOfWeek -eq 'Monday') {"Do Task"}

Do Task

but if you need the 1 and 3 monday, the example in blogpost is easer to adapt 

Greetings /\/\o\/\/

Tuesday, February 27, 2007 12:09 PM by MoW

# re: Hey, PowerShell Guy ! How Can I Tell If a Script is Running on the First or Second Monday of a Month?

What about this approach:

if ( ([datetime]$date).dayOfWeek -eq 'Monday' -and [math]::ceiling($date.Day/7) -lt 3) {"Do Task"}

I'm sure there is a fatal flaw in it somewhere....

Friday, March 16, 2007 4:12 PM by Don
Anonymous comments are disabled