TAGS :Viewed: 13 - Published at: a few seconds ago

[ If / else on powershell ]

I am currently learning how to use powershell and was wondering how would you make a simple process like this for example.

If the time is between 9am and 12pm then write to 'Get coffee' else write nothing.

Answer 1


There are a lot of ways to do this.

if ((9,10,11) -contains (get-date).Hour) { "get coffee" }

if ((get-date).hour -ge 9 -and (get-date).hour -le 11) { "get coffee" }

if (((get-date -hour 12 -min 0 -sec 0) - (get-date)).hours -in 0..2) { ... }

This might be a fun community wiki question.

Answer 2


This is about as short as I can get it...

if(Get-Date | ? {($_.hour -ge 9) -and ($_.hour -le 12)}){"get coffee"}

Answer 3


My 2 cents (using .net):

[datetime]$now = [datetime]::now.Tostring("T",[System.Globalization.CultureInfo]::InvariantCulture )
$low = [datetime] "09:00:00 am"
$hi = [datetime] "12:00:00 pm"
if ( $now -ge $low -and $now -le $hi  ) { "Coffee Time!" } else {"Work!"}