AddDays in powershell - powershell

I have a stored procedure which has 2 parameters #from, #to, I want to pass #from the value of $from, which is inputed from powershell GUI. I want #to to be 1 day after #from. I have below code. Which value seems to be passed to #from, but to value is not passed. Any suggestion?
$param1=$sqlcmd.Parameters.Add("#from" , [System.Data.SqlDbType]::DateTime)
$param1.Value=Get-Date $from -format "yyyy-MM-dd HH:mm:ss.fff"
$param2=$sqlcmd.Parameters.Add("#to", [System.Data.SqlDbType]::DateTime)
$param2.Value=Get-Date ($from).AddDate(1) -format "yyyy-MM-dd HH:mm:ss.fff"

If I recall correctly from your previous question, $from is a string, not a date. You can't add days to a string, so you need to convert it to a date first. Also you need .AddDays(1), not .AddDate(1).
$param2.Value = Get-Date (Get-Date $from).AddDays(1) `
-format "yyyy-MM-dd HH:mm:ss.fff"

Related

Powershell - Find the latest Friday

How can the following code be modified to identify the latest Friday within the past week (instead of the next one), but with formatting?
$Date = #(#(0..7) | % {$(Get-Date).AddDays($_)} | ? {$_.DayOfWeek -ieq "Friday"})[0]
Source: https://stackoverflow.com/a/23939203/5651418
The post you linked to offers a more elegant solution, which you can adapt as follows:
# Get the most recent Friday relative to the given date,
# which may be that date itself.
$mostRecentFriday =
($date = Get-Date).AddDays((-7 - $date.DayOfWeek + [DayOfWeek]::Friday) % 7)
If you want to create a formatted string representation of the resulting [datetime] instance (all examples below yield something like '07 01 2022':
To use Unix-style format specifiers, use Get-Date's -UFormat parameter:
Get-Date $mostRecentFriday -UFormat '%d %m %Y'
To use .NET's format specifiers, use Get-Data's -Format parameter:
Get-Date $mostRecentFriday -Format 'dd MM yyyy'
Alternatively, pass the format string to the [datetime]
instance's .ToString() method:
$mostRecentFriday.ToString('dd MM yyyy')
If I understood correctly, your expected output would be 1 7 2022, I would personally use a do loop that stops as soon as the DayOfWeek Property of the DateTime instance is Friday:
$date = [datetime]::Now
do {
$date = $date.AddDays(-1)
} until($date.DayOfWeek -eq [DayOfWeek]::Friday)
$date.ToString("d M yyyy")
I noticed that some Get-Date -UFormat specifiers didn't seem to work when attempting to incorporate them into an output string.
Should anyone need to incorporate some rarely needed ones (like 'Week of Year' (%G), 'Day of Year (%j), etc) you could preset needed variables and add them to the output string:
$DayOfYear = (Get-Date -UFormat %j)
$WeekOfYear = (Get-Date -UFormat %V)
$Date = #(#(0..7) | % {$(Get-Date).AddDays(-$_)} | ? {$_.DayOfWeek -ieq "Wednesday"})[0].ToString("MM-dd-yyyy|Week $WeekOfYear|'Day' $DayOfYear")
I imagine someone could incorporate all the code into one Powershell command.
Additional Get-Date -UFormat specifiers: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-date?view=powershell-7.2#notes

How convert a future date to the yyyy-mm-ddT00:00:00Z format with PowerShell

I am trying to get this to work in PowerShell with no success.
I would need to convert a future date and time (let's say July 1st 2022 midnight 00:00) to the format yyyy-mm-ddT00:00:00Z
The below command:
Get-Date -Format u
outputs to 2022-06-21 13:34:20Z (at the time of writing), which is pretty close to what i need for the present time.
Is there a way to get what i need without the use of regex or replace() method and also in the future?
The format is pretty flexible. Just specify it manually:
Get-Date -Format yyyy-MM-ddTHH:mm:ssZ
Output: 2022-06-21T03:51:17Z
For a future date, it's probably easier to create that in advance, then use it with the formatting:
$futuredate = (Get-Date).AddDays(30)
Get-Date $futuredate -Format "yyyy-MM-ddTHH:mm:ssZ"
Output: 2022-07-21T03:56:46Z
Or, if in your case you really do want exactly midnight for the day in question:
$futuredate = (Get-Date).AddDays(10).Date
Get-Date $futuredate -Format "yyyy-MM-ddTHH:mm:ssZ"
Output: 2022-07-01T00:00:00Z
Based on the above answer, i tried to come up with a version of getting the first day of the next month and the last day. Let me know your thoughts:
Beggining of month:
Get-Date -Format "yyyy-MM-ddT00:00:00Z" -Date ([datetime](Get-Date -Day 1).AddMonths(1))
Output: 2022-07-01T00:00:00Z
End of month:
Get-Date -Format "yyyy-MM-ddT23:59:59Z"-Date (([datetime](Get-Date -Day 1).AddMonths(2)).AddDays(-1))
Output: 2022-07-31T23:59:59Z

Substract a date with Powershell

Using Powershell I need to get a date in the "yyyyMMdd" format.
I can use $Date_Today = Get-Date -format "yyyyMMdd" and it works corerctly.
Now I need to get the date, a day ago:
(Get-Date).adddays(-1)
But If I need to get the date , a day ago in the same format I get an error:
((Get-Date).adddays(-1)) -format "yyyyMMdd"
Use the .ToString() function to get the desired result:
(Get-Date).adddays(-1).ToString("yyyyMMdd")

How to generated a timestamp based on another formatted timestamp

I'm attempting to output a timestamp in Powershell to represent the time now (rounded down to the 00 seconds), and another to represent 30 minutes before that. Both timestamps should be formatted yyyy-mm-ddThh:mm:ss.
If I use just Get-Date as when setting $end_time, then $start_time is set too.
$end_time = Get-Date
$start_time = $end_time.AddMinutes(-30)
However, when I format $end_time as required, an error occurs when settings $start_time. It looks like calling -Format returns the date as string rather than a date object.
$end_time = Get-Date -Format s -Second 00
$start_time = $end_time.AddMinutes(-30)
Method invocation failed because [System.String] does not contain a method
named 'addminutes'.
To try and work around this shortcomming I added a $date variable, but now I'm unable to even set $end_time. I guess this is because the formatting is returned by the Get-Date function, and cannot be set retrospectily.
$date = Get-Date
$end_time = $date -Format s -Second 00
Unexpected token '-Format' in expression or statement.
So my question is: if I am unable to manipulate a formatted date, and if I cannot format a pre-generated date as requred, how is it possible to generate two timestamps that are 30 minutes apart (one for 'now', one for 30 minutes ago) and which are formatted as yyyy-mm-ddThh:mm:ss?
Instead of using the -Format parameter of Get-Date, use the .ToString method on the date objects you create instead:
$Date = Get-Date -Second 0
$Date.ToString("yyyy-MM-ddTHH:mm:ss")
$Date.AddMinutes(-30).ToString("yyyy-MM-ddTHH:mm:ss")
Explanation:
Get-Date is executed and returns a DateTime object representing the current date and time with the seconds set to 0. This is then cast to a string using the .ToString method to format per your custom style.
The next command is the same, but before casting it as a formatted string (whereby it loses the date object methods), the .AddMinutes method is used to remove 30 minutes.
Keep $date as datetime, use ToString as required:
$date = Get-date -second 0
$end_time = $date.ToString("yyyy-MM-ddTHH:mm:ss")
$start_time = ($date.AddMinutes(-30)).ToString("yyyy-MM-ddTHH:mm:ss")

Change format of DateTimeReceived (Built-in feature from Microsoft)

I am working with email and its downloading and i want to set a condition to run a script with If {} only when email is received on the same day.
I do have this 2 lines of script:
$datetime = get-date -f yyyMMdd
$Sfha = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::DateTimeReceived, $datetime)
First declares today in the format of yyymmdd.
In order If condition to work, I also need to change format of DateTimeReceived.
You can pass date as a parameter to the get-date function, it can convert it to a specified format. You can try something like,
$datetime = get-date -f yyyyMMdd
$Sfha = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo((Get-Date ([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::DateTimeReceived) -Format yyyyMMdd), $datetime)