Convert day of year value to date in Powershell - powershell

In Powershell, converting a date into a day of the year value is easy:
$DayOfYear = (Get-Date).DayofYear
Write-Host $DayOfYear
140
Is there a similar way to convert the day of year back into a date (i.e. 140 = 05/20/2013)?

Try this:
([datetime]"01/01/$((Get-Date).Year)").AddDays(140-1)
20. mai 2013 00:00:00
mai = may in norwegian :-)

You could create a DateTime object representing the start of the year, then add the number of days to it, e.g.:
(New-Object System.DateTime 2013,1,1).AddDays(140-1)

This might be helpful for you:
$startdate_year = ([datetime]"01/01/$((Get-Date).Year)")
$a = (Get-Date $startdate_year).AddDays(139)
"Date: " + $a.ToShortDateString()
Now you will get the result like this:
Date: 5/20/2013

Use this method to avoid [datetime] objects and use Powershell syntax only:
$DayOfYear = (Get-Date).DayOfYear
$Today = (Get-Date -Month 1 -Day 1).AddDays($DayOfYear-1)
"$($Today.ToString("MM/dd/yyyy")) is day $DayOfYear of 365"
Output:
10/03/2017 is day 276 of 365

Related

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

Using powershell for a google report

I'm new to using powershell, I'm trying to use the PSGSuite module to get a report for all users for the past 30 days. What I've got so far is the following
$REQUESTEDDATE = Read-Host -Prompt 'Enter the month for the desired report month in numerical form. e.g Jan 1 Feb 2 Mar 3'
$REPORTDATE = (Get-Date -Month ($REQUESTEDDATE-(-1)) -Hour 0 -Minute 0 -Second 0)
$MonthAgo = $REPORTDATE.AddMonths(-1)
$FIRSTDAYOFMONTH=GET-DATE $MonthAgo -Day 1
$LASTDAYOFMONTH=GET-DATE $FIRSTDAYOFMONTH.AddMonths(1).AddSeconds(-1)
$Times = $FIRSTDAYOFMONTH..$LASTDAYOFMONTH.day | Foreach-Object {
$currentdate = Get-Date -Day $_ -Month $LASTDAYOFMONTH.Month -Year $LASTDAYOFMONTH.Year
$GMAIL = Get-GSUsageReport -Date $currentdate -UserKey xxx -flat
}
This is now throwing a "Invalid cast from 'DateTime' to 'Int32' error. There's probably a much easier way to do this, but I'm more of the hardware/networking side thrown onto this while the dev team is working on different projects, so any help is appreciated.
First thing is that I hate all those CAPITALS in your code, so if you don't mind I have changed that.
Next, you can simply run through the dates for as long as the running date is less than the final date (day 1 of the requested date) using a while loop:
$requestedDate = Read-Host -Prompt 'Enter the month for the desired report month in numerical form. e.g Jan 1 Feb 2 Mar 3'
$reportDate = (Get-Date -Month $requestedDate -Day 1).Date # end date set at midnight on day 1
$runningDate = $reportDate.AddMonths(-1) # start at day 1, one month ago
$result = while ($runningDate -lt $reportDate) {
# perform your command and capture the output in variable $result
Get-GSUsageReport -Date $runningDate -UserKey xxx -flat
# increment the running date
$runningDate = $runningDate.AddDays(1)
}
# show the result
$result

Subtracting time in powershell

I use the following time code:
$time = [DateTime]::UtcNow | get-date -Format "yyyyMMddHH"
$m2=$time-02 # trying to subtract 2 hours
However, for times like 2021021701, subtracting 2 gives me 2021021699. How can I have the time display in the correctly?
Another way. The 2nd arg can be a datetime or a timespan. $time is a datetime.
$time = get-date
$m2 = $time - [timespan]'2:0'
$m2
Wednesday, February 17, 2021 7:31:59 PM
To perform date calculations, operate on [datetime] (System.DateTime) instances and use that type's methods, such as .AddHours(); only after that should you create the desired string representation:
# Get the current UTC time as a [datetime] instance.
$time = [DateTime]::UtcNow
# Subtract 2 hours.
$m2Time = $time.AddHours(-2)
# Create the desired string representation.
$m2 = Get-Date $m2Time -Format 'yyyyMMddHH'

Powershell get date from log file

I would like to get date from the log file text.
Text in log file.
Error code. 200105. Simple text and so on -------------> it should get date as 2020 Jan 05
Error code. 2000207. Simple text and so on -------------> it should get date as 2020 Feb 07
I try this but it doesnt work.
Get-Date "200105" -format "y-m-d" but it doesnt work.
I also try "200105" | Date but still same issue
This does work [datetime]::ParseExact("120105", "y.m.d", $null) but how do I get just the date but ignore all of the other text
If you want a shorter version you can do that by piping the output as follows
$date = [datetime]::ParseExact($text2, "y.M.d", $null)
$date | Get-Date -Format dd-MMMM-yyyy
Or
$date.ToString("yyyy MMMM dd")
Your second example 2000207 is invalid because of the extra 0 in there.
I would use the TryParseExact method here to see if what you have got is actually a parsable datetime string.
$logLine = 'Error code. 200105. Simple text and so on'
if ($logLine -match '^Error code\s*\.?\s*(\d{6})') {
$date = Get-Date # any valid DateTime object will do
if ([datetime]::TryParseExact($Matches[1], 'yyMMdd', [cultureinfo]::InvariantCulture, 0, [ref]$date)) {
# do something with the date found. For demo, just output in the console
"Found a date: $date"
}
}
You are probably reading the log file line-by-line, something like:
Get-Content -Path 'TheLogFile' | ForEach-Object {
if ($_ -match '^Error code\s*\.?\s*(\d{6})') {
$date = Get-Date # any valid DateTime object will do
if ([datetime]::TryParseExact($Matches[1], 'yyMMdd', [cultureinfo]::InvariantCulture, 0, [ref]$date)) {
# do something with the date found. For demo, just output in the console
"Found a date: $date"
}
}
}
According to the documentation, Get-Date converts a string to a date if it recognises the date format from the locale settings.
For instance, in UK it recognises Get-Date "2020/03/21" but not Get-Date "20200321"
The format string is only used for formatting the current date.
This works: the number of characters in the format string represents the size of the input (it matches the number of digits in the day and year - it is more complicated for months) and M represents months (m represents minutes).
PS /home/alistair> [datetime]::ParseExact("200321","yyMMdd",$null)
Saturday, 21 March 2020 00:00:00

PowerShell date/time conversion

I have a variable, $date, containing 24 June 2012 00:00:00.
How do I convert this to 24/06/2012?
Use the Get-Date cmdlet together with the Format parameter:
PS> $date = '24 June 2012 00:00:00'
PS> Get-Date $date -Format 'dd/MM/yyyy'
24/06/2012
I tried reading a file with dates formatted day-month-year
The answer above did not work for me, I found a different solution on how to parse my dates and check which one is newer than the current date. This is my adapted code.
$currdateobj = Get-Date
$STARTDATE = "12-05-2017" // specific non-default date format
[DateTime]$startdateobj = [DateTime]::ParseExact($STARTDATE,"dd-MM-yyyy",[System.Globalization.CultureInfo]::InvariantCulture)
if ($startdateobj -lt $currdateobj)
{
// ....
}