Using a Powershell date object how do you get the day number of the week, 0 to 6 where 0 would be Sunday and 6 would be Saturday. I know that I can get the day name with the code below but how do I get the number as there is no DayNumberOfWeek or equivalent property?
(Get-Date).DayOfWeek
I suppose I could use the day name from the code above in a switch statement to convert it to a number but that doesn't seem to be very eloquent.
like this:
( get-date ).DayOfWeek.value__
I suggest for the future to investigate what properties an object in this way:
( get-date ).DayOfWeek | gm -f # gm is an alias for get-member
Well, the DayOfWeek property of a DateTime is not a string but rather a DayOfWeek enum, so the shortest answer is probably
[Int] (Get-Date).DayOfWeek # returns 0 through 6 for current day of week
Or
[Int] [DayOfWeek] "Wednesday" # returns 3
Get-Date -UFormat %u
will return formated date.
check http://technet.microsoft.com/en-us/library/hh849887.aspx for more fomats
On Friday the 17th:
(get-date).DayOfWeek.value__
Returns 5
(Get-Date).DayOfWeek
Returns Friday
(Get-Date).Day
Returns 17
Related
I have an use case where user passes a date from the past. But I need to check if it's a Wednesday. If not, I want to be able to set it to next Wednesday 5 AM. Can somebody please tell me what would be best approach to go about this using PS?
Thanks.
Fortunately [datetime] structs have a DayOfWeek property we can use to check that!
Simply advance the date by 1 day at a time until you reach Wednesday:
function Get-UpcomingWednesdayAt5
{
param(
[datetime]$Date
)
while($Date.DayOfWeek -ne [System.DayOfWeek]::Wednesday){
# advance 1 day at a time until its wednesday
$Date = $Date.AddDays(1)
}
# Create new [datetime] object with same Date but Time set to 5AM
return Get-Date -Date $Date -Hour 5
}
Using powershell 5.1
I have a function called that returns a string representing a date like this
"4/22/2019 12:00:00 AM"
function Get-LastLogTime() {
$lastRunDate = Get-SQLData "." "AdHoc" "SELECT TOP 1 o.LogTime FROM dbo.FAQlog o WHERE o.RecordsSent = 1 ORDER BY o.LogTime DESC"
return $lastRunDate
}
Where LogTime is the usual Datetime SQL type and Get-SQLData is another function that returns a datatable.
If I just check the return value, I get something like this
LogTime
-------
4/22/2019 12:00:00 AM
Ok, great, but I need to compare this date to the current date. So, I do something like this but i get an error on the line trying to convert $testDate to datetime.
# test
$testDate = Get-LastLogTime
([DateTime]$testDate) -lt (Get-Date)
If I just do a simple comparison at the command line, it works, eg.
([DateTime]"4/22/2019 12:00:00 AM" ) -lt (Get-Date)
It works with
([DateTime]"4/22/2019 12:00:00 AM" )
Because you are casting DateTime on a String.
Return value of Get-LastLogTime is not a string probably and casting it to a Datetime does not work.
get-LastLogTime | get-member will show you the methods you have available on the returned data type such as, for instance, ToString, and that can be used to perform the comparison.
I want to get the last Monday date for the given date. For example If my input is 190113 I want the output as 190107 which is last Monday.
if {$current_date == "Mon"} {
set startday [clock seconds]
set startday [clock format $startday -format %y%m%d]
puts $startday
} else {
puts "no monday today"
#I don't know how to get last monday date
}
This can be done fairly simply, by taking advantage of the fact that clock scan has quite a complex parser, and you can supply a timestamp that everything is relative to via the -base option. Also, both clock scan and clock format take -format options so that you can specify exactly what is going on in your input and output data.
proc getLastMonday {baseDate} {
set base [clock scan $baseDate -format "%y%m%d"]
set timestamp [clock scan "12:00 last monday" -base $base]
return [clock format $timestamp -format "%y%m%d"]
# This would work as a one-liner, provided you like long lines
}
Demonstrating:
puts [getLastMonday 190113]; # ==> 190107
puts [getLastMonday 190131]; # ==> 190128
Reference: https://www.tcl.tk/man/tcl/TclCmd/clock.htm#M22
Here's a sample code-snippet for the purpose. Added inline comments for understanding:
proc get_last_monday_date {date} {
# Get the end timestamp for the specified date
set end_timestamp [clock scan ${date}-23:59:59 -format %y%m%d-%H:%M:%S]
# Get day of the week for the current date
set day_of_week [clock format $end_timestamp -format %u]
# Sunday may report as 0 or 7. If 0, change to 7
# if {$day_of_week == 0} {
# set day_of_week 7
# }
# Monday is 1st day of the week. Monday = 1.
# Find how many days to go back in time
set delta_days [expr $day_of_week - 1]
# Multiply the delta by 24 hours and subtract from end of the day timestamp
# Get the timestamp for the result. That's last Monday's timestamp.
return [clock format [clock add $end_timestamp -[expr $delta_days * 24] hours] -format %D]
}
puts "Last Monday for 01-Jan-2019: [get_last_monday_date 190101]"
puts "Last Monday for 06-Jan-2019: [get_last_monday_date 190106]"
puts "Last Monday for 15-Jan-2019: [get_last_monday_date 190115]"
puts "Last Monday for 31-Jan-2019: [get_last_monday_date 190131]"
Execution output:
Last Monday for 01-Jan-2019: 12/31/2018
Last Monday for 06-Jan-2019: 12/31/2018
Last Monday for 15-Jan-2019: 01/14/2019
Last Monday for 31-Jan-2019: 01/28/2019
Is it possible to compare 2 custom dates. Am trying check if variables hold date1 is lessthan date2, if so, report saying date1 is older date.
I getting both dates from a. date1 from log file and date2 from application itself
now, both date1 and date2 are in required format ie,
$Date1 = Tue,Aug 16, 2016 12:40:03
$Date2 = Mon,Aug 22, 2016 16:33:02
my next step is compare these 2 dates and report if date1 is older date compare to Date2, which I don't know how to proceed.. Any help/ideas is much appreciated.
Thanks to Pete and Ansgar Wiechers
updated working Code :
$Date1DateTime = [DateTime]::ParseExact($Date1,'ddd,MMM d, yyyy, HH:mm:ss',[Globalization.CultureInfo]::InvariantCulture); $Date2DateTime = [DateTime]::ParseExact($Date2,'ddd,MMM d, yyyy, HH:mm:ss',[Globalization.CultureInfo]::InvariantCulture); $Date1DateTime -lt $Date2DateTime
You can only compare date strings if the string sort order is the same as the date sort order. For instance, date strings in ISO format are comparable:
2016-08-16T12:40:03
2016-08-22T16:33:02
Date strings in your custom format are not, because T comes after M, but August 16 should actually come before August 22:
Tue,Aug 16, 2016 12:40:03
Mon,Aug 22, 2016 16:33:02
If you don't have the date strings in ISO format it's usually better to parse them into actual DateTime values (as #PetSerAl suggested), particularly if your reference value is originally a DateTime anyway.
$fmt = 'ddd,MMM d, yyyy, HH:mm:ss'
$culture = [Globalization.CultureInfo]::InvariantCulture
$Date1 = Get-Date $LogFileDate
$val = (b2b.exe -readparams $param | Select-Object -Skip 1 -First 1) -split '='
$Date2 = [DateTime]::ParseExact($val[1], $fmt, $culture)
if ($Date1 -lt $Date2) {
...
}
Morning All,
I have a variable as follows: $machines = $user2,$name,$serial,$purchased
sample data stored in $machines is:
User1,
Laptop1,
xyz1234,
01/01/2010
I am wanting to create a new variable called $tobereplaced containing all of the records in $machines with a date greater than 4 years old from todays date.
the fuzzy logic code for this im expecting to be someting like $tobereplaced = $machines.$purchased | where {$_$purchased = -getdate > 4 years} etc etc but i cant quite figure it out.
Assistance would be greatly appreciated.
Thanks
$fourYearsAgo = (Get-Date).AddYears(-4)
$tobereplaced = $machines | Where-Object { (Get-Date $_[-1]) -le $fourYearsAgo }
Convert the date as DateTime and compare it against a date four years ago. Like so,
# Assuming $m[3] contains the timestamp, parse it as a DateTime and compare
# against a date four years ago.
if([DateTime]::Parse($m[3]) -le [DateTime]::Now.AddYear(-4)) {
$tobereplaced += $m
}
Depending on your locale, you might need to tell [DateTime]::Parse() how to parse the date. Is 01/12/2010 1st of December, 2010 or 12th January, 2010?