Powershell script to check if given hours is between working hours - powershell

What I've done is to get the current hour and then compare it to a string that I get as an output from a system that I split to get the starting hour and ending hour.
The check keeps showing up as True no matter what the time is
$current_day = Get-Date -Format "dddd"
$current_hour = Get-Date -Format "HH:mm"
$string = "Sat 16:00 to 00:00".Split(" ")
$day = $string[0]
$from_hour = Get-Date $string[1] -Format "HH:mm"
$to_hour = Get-Date $string[3] -Format "HH:mm"
Write-Output("CURRENT TIME: {0} {1}" -f $current_day, $current_hour)
Write-Output("GIVEN TIME: {0} from {1} to {2}" -f $string_day, $string_from_hour, $string_to_hour)
if($current_hour -le $from_hour -and $current_hour -ge $to_hour)
{
return $true
}
else
{
return $false
}

Your code does work with just a few small changes.
The most critical is just swapping the operators around for your if statement
Write-Output("GIVEN TIME: {0} from {1} to {2}" -f $string_day, $from_hour, $to_hour)
if($current_hour -ge $from_hour -and $current_hour -le $to_hour)
Finally, instead of comparing to 00:00 midnight, change the end time to 23:59 which is close enough for government work. With these two things done, it works.
CURRENT TIME: Thursday 19:13
GIVEN TIME: from 16:00 to 23:59
True

You can try something like this:
$StartTime = "16:00";
$EndTime = "00:00"
$EndTime_ = (Get-Date $EndTime).AddDays(1);
if (((Get-Date) -gt (Get-Date $StartTime)) -and ((Get-Date) -lt ($EndTime_))) {
Get-Date -Format "hh:mm";
}
else {
$false
}

Thanks everyone for their suggestions.
I couldn't miss a minute as the script is intended to run per hour.
So what I've done is to convert 00:00 into 99:99 (both current time and working hours) and it works flawlessly.

Related

How to do time "HH:mm" comparison in Powershell?

Apparently my code is like this and it is now working. I think the logic is already there. the $openTime and $closeTime is read from csv using import-csv in "HH:mm" form.
$openTime = $ip.openTime
$closeTime = $ip.closeTime
$time = Get-Date -UFormat "%R"
if (($time -ge $openTime) -and ($time -le $closeTime)) {
Write-Host "Store is Open!" -ForegroundColor Green
}else{
Write-Host "Store is outside open hours!" -ForegroundColor Red
}
powershell 7
$csv = #"
store, openTime, closeTime
Wallmart, 08:00, 18:00
Ikea, 10:00, 20:30
"# | ConvertFrom-Csv
Get-Date
$csv | ForEach-Object{
[int]([datetime]::Now - [datetime]::Today).TotalMinutes -in (.{[int]$args[0][0]*60 + [int]$args[0][1]} $_.openTime.split(":"))..(.{[int]$args[0][0]*60 + [int]$args[0][1]} $_.closeTime.split(":")) ? "Store {0} is Open! " -f $_.store : "Store {0} is outside open hours!" -f $_.store
}
16 февраля 2021 г. 8:52:42
Store Wallmart is Open!
Store Ikea is outside open hours!
powershell 5
$csv = #"
store, openTime, closeTime
Wallmart, 08:00, 18:00
Ikea, 10:00, 20:30
"# | ConvertFrom-Csv
Get-Date
$csv | ForEach-Object{
("Store {0} is outside open hours!", "Store {0} is Open! ")[[int]([datetime]::Now - [datetime]::Today).TotalMinutes -in (.{[int]$args[0][0]*60 + [int]$args[0][1]} $_.openTime.split(":"))..(.{[int]$args[0][0]*60 + [int]$args[0][1]} $_.closeTime.split(":"))] -f $_.store
}
Try it online!
I find it's much easier to work with date and times if I convert them to [DateTime] objects. We can use the DateTime class method ParseExact to convert the time into [DateTime] objects for us. This object will actually contain today's date as well as the time we supply, but for our purposes this is fine since the $time object also will be today's date. For the current time ($time) just let Get-Date return to us a [DateTime] object that will represent the current date and time (now). After that the rest of your code works as expected. Hurray!
# this $ip hashtable object just represents data similar to your csv import
$ip = #{
openTime = "09:00"
closeTime = "21:00"
}
$openTime = [datetime]::ParseExact($ip.openTime, 'HH:mm', $null)
$closeTime = [datetime]::ParseExact($ip.closeTime, 'HH:mm', $null)
$time = Get-Date
if (($time -ge $openTime) -and ($time -le $closeTime)) {
Write-Host "Store is Open!" -ForegroundColor Green
}
else {
Write-Host "Store is outside open hours!" -ForegroundColor Red
}
If you are working with the time are imported from csv, make sure the time format in the csv file is in "HH:mm"

datetime comparison letting thread proceed when shouldn't

I have a backup script that puts files in a dated directory every night. I have another script, below, that goes through a list of dated directories and if it's within the range I want to delete, I will delete the directory, keeping the Saturday dated file. For some reason, for the dir dated Saturday, 1/12/2019, it's being deleted, even though the if statement should indicate it wouldn't be deleted.
This is my code:
function WeeklyCleanup($folderWeeklyCleanupDatedSubdirs) {
#find out date range to cleanup
$lastSaturday = GetLastSaturdayDate
$lastSaturday = [datetime]$lastSaturday
$weekAgoSunday = GetWeekAgoSundayDate
$weekAgoSunday = [datetime]$weekAgoSunday
#find out filename with Saturday date before current date but within week
Get-ChildItem $folderWeeklyCleanupDatedSubdirs | ForEach-Object {
write-output $_
#check to see if item is before day we want to remove
$temp = $_
$regex = [regex]::Matches($temp,'([0-9]+)-([0-9]+)-([0-9]+)')
if($regex.length -gt 0) #it matched
{
$year = $regex[0].Groups[1].Value
$month = $regex[0].Groups[2].Value
$day = $regex[0].Groups[3].Value
write-output $year
write-output $month
write-output $day
write-output "*************"
$dirDate = $regex[0].Groups[0].Value + " 12:00:00 PM"
write-output $dirDate
if($dirDate.length -gt 0) #it matched
{
$dateTimeObjectFromRegex = [datetime]$dirDate
##########this next statement is letting $dateTimeObjectFromRegex of 1/12/2019 through when it shouldn't. See time comparison below
if(([datetime]$dateTimeObjectFromRegex -lt [datetime]$lastSaturday) -and ([datetime]$dateTimeObjectFromRegex -ge [datetime]$weekAgoSunday)) #we're removing extra ones over last week, keep Saturday
{
$dirPathToRemove = Join-Path -path $folderWeeklyCleanupDatedSubdirs -ChildPath $temp.ToString()
Get-ChildItem -Path $dirPathToRemove #list the dir
#remove dir
if(-Not (Test-Path $dirPathToRemove )) #-PathType Container
{
$global:ErrorStrings.Add("Exception: No such path, $dirPathToRemove;; ")
write-output "++ Error: An error occured during copy operation. No such path, $dirPathToList ++"
}
else
{
#remove dir and subdirs
Remove-Item $dirPathToRemove -Force -Recurse
Get-ChildItem -Path $dirPathToRemove #list the dir
}
#Write-Output $_
#Write-Output " 1 "
} #if within last week
} #if dirDate length
} #if regex matched
} #get-childItem
}
function GetLastSaturdayDate()
{
$date = Get-Date #"$((Get-Date).ToString('yyyy-MM-dd'))"
#for($i=1; $i -le 7; $i++){
# if($date.AddDays(-$i).DayOfWeek -eq 'Saturday') #if found Saturday
# {
# $date.AddDays(-$i)
# $newDate = $date.AddDays(-$i)
# break
# }
#}
$newdate = $date.AddDays(-($date.DayOfWeek+1)%7)
return $newdate
}
function GetWeekAgoSundayDate()
{
$numberOfWeeks = 1; #week ago
$date = Get-Date #"$((Get-Date).ToString('yyyy-MM-dd'))"
#for($i=1; $i -le 7; $i++){
# if(($date.AddDays(-$i).DayOfWeek -eq 'Sunday') -and ($date.AddDays(-$i) -ne $date)) #if found a Sunday and it's not today
# {
# $date.AddDays(-$i)
# $newDate = $date.AddDays(-$i)
# break
# }
#}
#$newdate = $date.AddDays(-($date.DayOfWeek+1)%0)
$numDaysSincePreviousDate = $date.DayOfWeek.value__ + 0 #0 is Sunday
([System.DateTime] $previousDayOfWeek = $date.AddDays(- $numDaysSincePreviousDate)) | Out-Null
$previousDate = $previousDayOfWeek.AddDays(-($numberOfWeeks *7)).ToString("MM-dd-yyyy")
return $previousDate
}
The WeeklyCleanup script is called with this parameter:
$folderToCleanupDatedSubdirs = [System.IO.DirectoryInfo]"E:\Bak_TestDatedFolderCleanup"
For time comparison:
Directory item toLocRobo_2019-01-12 - Once I get regex with timestamp, I add the time in of 12:00:00 PM for the $dirDate variable. This becomes $dateTimeObjectFromRegex. Debugger shows it as Saturday, January 12, 2019 12:00:00 PM
When I run the program, I get $lastSaturday as Saturday, January 12, 2019 3:59:04 PM
When I run the program, debugger also shows $weekAgoSunday as Sunday, January 6, 2019 12:00:00 AM
From what I can see, it shouldn't be getting through that if statement to delete the dir for 1/12/2019.
I tried casting the dates to datetime to make sure it wasn't doing a string comparison in the if statement, even though I casted it above.
I've been looking at these links for more info on this, but it looks correct to me:
dateTimeComparisons not working expectedly
convert string to datetime
All I can think is that it's still treating the datetime in the first part of the if statement comparison like a string, so it's thinking 3:59 PM is greater than 12:00 PM. Any ideas how to get this date check to work? I don't care about times, just want to make sure it doesn't get rid of the Saturday-dated file from this past week, but only cleanup other dir's over that week.
Update
Made changes suggested by #brianist below, and it worked great. This is what it looks like so far. Saturday and Sunday functions haven't changed. He's asking me to post it. If he has any other suggestions how to get it to treat/compare what's returned from the last Saturday and weekAgoSunday functions as dates, without the cast, that'd make it look less clunky/easier to read. Thanks Brian!
#do weekly cleanup of DisasterBackup folder
function WeeklyCleanup($folderWeeklyCleanupDatedSubdirs) {
#find out current date
$currentDate = "$((Get-Date).ToString('yyyy-MM-dd'))" #example 2019-01-15
$currentDayOfWeek = (get-date).DayOfWeek.value__ #returns int value for day of week
#find out current day of week
$lastSaturday = GetLastSaturdayDate
$lastSaturday = [datetime]$lastSaturday #if we take away extra casts it won't do comparison line (-lt and -ge)
$weekAgoSunday = GetWeekAgoSundayDate
$weekAgoSunday = [datetime]$weekAgoSunday #if we take away extra casts it won't do comparison line (-lt and -ge), and can't move cast before function call because it isn't recognizing function anymore if I do
#find out filename with Saturday date before current date but within week
#get each dir item to check if we need to remove it
Get-ChildItem $folderWeeklyCleanupDatedSubdirs | ForEach-Object {
write-output $_
#check to see if item is before day we want to remove
$temp = $_
if($_.Name -match '(\d{4}-\d{2}-\d{2})$'){ #regex
write-output $Matches[1]
$dirDate = Get-Date $Matches[1] #turn regex into date
if(([datetime]$dirDate.Date -lt [datetime]$lastSaturday.Date) -and ([datetime]$dirDate.Date -ge [datetime]$weekAgoSunday.Date)) #we're removing extra ones over last week, keep Saturday
{
$dirPathToRemove = Join-Path -path $folderWeeklyCleanupDatedSubdirs -ChildPath $temp.ToString()
Get-ChildItem -Path $dirPathToRemove #list the dir
#remove dir
if(-Not (Test-Path $dirPathToRemove )) #-PathType Container
{
$global:ErrorStrings.Add("Exception: No such path, $dirPathToRemove;; ")
write-output "++ Error: An error occured during copy operation. No such path, $dirPathToList ++"
}
else
{
#remove dir and subdirs
Remove-Item $dirPathToRemove -Force -Recurse
Get-ChildItem -Path $dirPathToRemove #list the dir
}
} #if within last week
} #if regex matched
} #get-childItem
}
Re-reading your last sentence, I now see that your intention is to ignore times, not to include them in your comparison.
You are right to want to use [DateTime] objects when comparing, but do note that those objects always include a time.
Conveniently you can use the .Date property of such an object which returns a new one, with the time set to midnight. This is useful for comparing because the time would no longer be a factor.
Pulling out my modified if statement from below, you can do it like this:
if ($dirDate.Date -lt $lastSaturday.Date -and $dirDate.Date -ge $weekAgoSunday.Date) {
# do stuff
}
Now you're only comparing dates, and ignoring time!
Based on what you're showing it looks like the if statement is working as expected. To summarize, you say that:
$dateTimeObjectFromRegex is Saturday, January 12, 2019 12:00:00 PM
$lastSaturday is Saturday, January 12, 2019 3:59:04 PM
$weekAgoSunday is Sunday, January 6, 2019 12:00:00 AM
The conditional is:
if(([datetime]$dateTimeObjectFromRegex -lt [datetime]$lastSaturday)
-and ([datetime]$dateTimeObjectFromRegex -ge [datetime]$weekAgoSunday))
Therefore in pseudo-code it's:
if (
("January 12, 2019 12:00:00 PM" is earlier than "January 12, 2019 3:59:04 PM") # true
and
("January 12, 2019 12:00:00 PM" is later or the same as "January 6, 2019 12:00:00 AM") # true
) # true
I do want to point out that you are doing an awful lot of unnecessary datetime chopping and casting, and cleaning that up would help with readability and with debugging these types of issues.
$lastSaturday = GetLastSaturdayDate
$lastSaturday = [datetime]$lastSaturday
$weekAgoSunday = GetWeekAgoSundayDate
$weekAgoSunday = [datetime]$weekAgoSunday
Your functions already return [DateTime] objects, so there's no need for those casts.
$temp = $_
$regex = [regex]::Matches($temp,'([0-9]+)-([0-9]+)-([0-9]+)')
if($regex.length -gt 0) #it matched
{
$year = $regex[0].Groups[1].Value
$month = $regex[0].Groups[2].Value
$day = $regex[0].Groups[3].Value
write-output $year
write-output $month
write-output $day
write-output "*************"
$dirDate = $regex[0].Groups[0].Value + " 12:00:00 PM"
write-output $dirDate
This is quite complex, you could simplify it down to something like this:
if ($_.Name -match '(\d{4}-\d{2}-\d{2})$') {
# in here, you know the match was successful
$dirDate = Get-Date $Matches[1] # double check this, might need .Groups or something
if ($dirDate -lt $lastSaturday -and $dirDate -ge $weekAgoSunday) {
# do stuff
}
}
Probably some more optimizations etc. Hope this was helpful!

convert date time to Epoch format in CSV in powershell

I want to convert datetime to Epoch format in csv file using PowerShell. In the csv file I have only time data, and I want to use current date and time specified in csv to convert it to Epoch format .
in.csv
"192.168.1.2","01-any1TEST ","Ping","Down at least 3 min","17:25:14",":Windows 2012 Server"
"192.168.1.2","02-any2TEST ","Ping","Down at least 4 min","17:25:40",":Unix Server"
"192.168.1.2","03-any3TEST ","Ping","Down at least 3 min","17:26:21",":windows host "
My findings
This should be doable using a combination of the below two. The main issue I am facing is that I am unable to combine the current date with the time in csv file.
Import-Csv ".\out.csv" |
ForEach-Object {
$_.Date = [datetime]::Parse($_.Date).ToString('MM/dd/yyyy HH:mm')
}
Get-Date -Date "12/31/2015 23:59:59" -UFormat %s
When using Get-Date, you have the option to override values manually or using another datetime
For example:
Import-Csv ".\out.csv" |
ForEach-Object {
$tempDate = [datetime]::Parse($_.Date).ToString('MM/dd/yyyy HH:mm')
Get-Date -Hour $tempDate.Hour -Minute $tempDate.Minute -UFormat %s
}
I'd do it like this:
Import-Csv ".\out.csv" |
ForEach-Object {
$_.Date = Get-Date -Date $_.Date -UFormat %s
}
If you want to be a bit more explicit about what it's doing, you can convert the time to a timespan, which can be added to a date. Then you can pipe it to Get-Date to format it:
Import-Csv ".\out.csv" |
ForEach-Object {
$_.Date = [DateTime]::Today + [Timespan]::Parse($_.Date) | Get-Date -UFormat %s
}
[DateTime]::Today is today's date at midnight (time 00:00:00).
Ok, try the code below. It will write a warning message to the console when it finds a date that it can't parse. It won't fix the problem, but it will tell you where the problem is.
Import-Csv ".\out.csv" |
ForEach-Object {
$t = [timespan]::Zero
if ([Timespan]::TryParse($_.Date,[ref]$t)) {
$_.Date = [DateTime]::Today + $t | Get-Date -UFormat %s
}
else {
Write-Warning "Unable to parse timespan '$($_.Date)' for record $($_)"
}
}
This is working perfectly for me in 2.0 and not on 4.0 version . If possible please let me know why is is not working on powershell 4.0 .
$EventTime = $($s.EventTime)
$value = get-date -format d
$Imported = Import-Csv 'C:\PathToFIle\out.csv'
$Output = foreach ($i in $Imported) {
foreach ($c in $EventTime) {
$time=$i.eventtime
$fulltime =$value+' '+$time
$i.EventTime = Get-Date -Date $fulltime -UFormat %s
}
$i
}
$Output
$Output | Export-Csv 'C:\PathToFIle\TestComputers.csv' -NoTypeInformation

Date format not applied when doing AddDay

I've got the following two queries:
$startDate = (Get-Date -format s).AddDays(-6)
$endDate = (Get-Date -format s)
Write-Host $startDate
Write-Host $endDate
//Prints
2015-05-02 16:23:52
2015-05-08T16:47:56
I'd like to understand how to put the T back in the first printed dates. The space breaks my powershell script where I add that date to an LogParser.sql path:
Myquery.Sql?startdate='$startdate'+enddate='$enddate')
This line:
$startDate = (Get-Date -format s).AddDays(-6)
throws an error (about [system.string] not having a function AddDays) for me with powershell 3.0.
I can get the output you want from this though:
"{0:s}" -f (Get-Date).AddDays(6)

Check if date in past

$olddate = Get-Date -Date "31-dec-2013 00:00:00" -Format d.M.yyyy
$Now = Get-date -Format d.M.yyyy
How can I check if $olddate is earlier than $Now?
If your store them as DateTime instead of as formatted strings, you can use the less-than operator (-lt) just like with regular numbers, and then use the format operator (-f) when you need to actually display the date:
$olddate = Get-Date -Date "31-dec-2013 00:00:00"
$Now = Get-Date
if($olddate -lt $Now){
"`$olddate is in the past!"
"{0:d.M.yyyy}" -f $olddate
"{0:d.M.yyyy}" -f $Now
}
You can also do a comparison on Ticks. I.e.: $olddate.Ticks will be -lt then $Now.Ticks.