Author Posts

June 13, 2017 at 3:03 pm

We would like to execute something by 9 PM daily on the device and if by change the device is offline by that time and boots up by 7 AM next day, then it should not run the program. So I used the following logic, but could not get the required result

[int]$h = Get-Date -Format HH

If($h -lt 20 -or $h -gt 7) then {do something } else {exit out}

Any help please ?

June 13, 2017 at 3:23 pm

$Hour24  = (Get-Date).Hour
if ($Hour24 -gt 21 -or $Hour24 -lt 7) { run task } else { don't run task }

June 13, 2017 at 3:25 pm

This gives me incorrect results. How about using like this ?
If($h -gt $Afterhr -xor $h -lt $Beforehr)

June 13, 2017 at 3:42 pm

Can you detail what you mean by incorrect result?

1..24 | % { 
    $Hour24 = ((Get-Date).AddHours($_)).Hour
    if ($Hour24 -gt 21 -or $Hour24 -lt 7) { "$Hour24 run task" } else { "$Hour24 don't run task" } 
}
12 don't run task
13 don't run task
14 don't run task
15 don't run task
16 don't run task
17 don't run task
18 don't run task
19 don't run task
20 don't run task
21 don't run task
22 run task
23 run task
0 run task
1 run task
2 run task
3 run task
4 run task
5 run task
6 run task
7 don't run task
8 don't run task
9 don't run task
10 don't run task
11 don't run task

June 13, 2017 at 3:46 pm

Oops my bad. It's working as expected. Thanks once again.

Also is there a way we can pass the logical operators (-gt, -lt) as a command line argument.

I am trying the following

[Parameter(Mandatory=$false)]
[ValidateSet('-lt','-gt')]
[string]$LOpert = '-lt',

If($h $LOpert 21 -or $h $LOpert 7) { run task } else { don't run task }

Command line is

DP.ps1 -LOpert -lt

June 14, 2017 at 6:28 am

You could use Invoke-Expression:

[Parameter(Mandatory=$false)]
[ValidateSet('lt','gt')]
[string]$LOpert = 'lt'

If((Invoke-Expression "$h -$LOpert 21 -or $h -$LOpert 7")) { run task } else { don't run task }

June 23, 2017 at 3:51 pm

Thanks everyone!!!