Formatting date and time in PowerShell - powershell

I want yesterday's date as "MMdd", like "0418" today's date is "0419".
I tried this:
$d = (Get-Date).AddDays(-1) | select -Property Month,Day
$e = $d.Day
$d = $d.Month
$total = "$d" + "$e"
Write-Host $total
But the output was "418".
As you can see, this is a three-letter string, but I want a four-letter one. Because I want to search files they have that format and created a day before.

The date object has a method ToString, which allows you to specify the format:
$d = (Get-Date).AddDays(-1);
$d.ToString("MMdd");
I am calling this on April the 20th, and the output is
0419
See this link for a description of the available date format strings.

Related

How to get all dates of the week based on week number using powershell?

I'm using powershell 7.x and want to create an array of dates in a week based on the weeknumber. I'm able to generate the array and find the whole week dates but how can I get the date values returned in the output?
I have used [System.Globalization.ISOWeek]::ToDateTime([Int32] year,[Int32] week number,[DayOfWeek]:Monday), to fetch the days of the week. Is there a better and optimal way to fetch all the dates in the array based on the week number?
Here's the code below:
function fetchWeekDates {
$output = #{ Monday =[System.Globalization.ISOWeek]::ToDateTime(2022,1,[DayOfWeek]::Monday)}
$output += #{ Tuesday=[System.Globalization.ISOWeek]::ToDateTime(2022,1,[DayOfWeek]::Tuesday)}
$output += #{ Wednesday =[System.Globalization.ISOWeek]::ToDateTime(2022,1,[DayOfWeek]::Wednesday)}
.
.
.
$output += #{ Sunday =[System.Globalization.ISOWeek]::ToDateTime(2022,1,[DayOfWeek]::Sunday)}
return $output
}
Expected output:
Output
-------
01-03-2022
01-04-2022
01-05-2022
01-06-2022
01-07-2022
01-08-2022
01-09-2022
The following function accepts a week number, and optionally a year (defaults to the current) and the day of the week that is considered the start of a week (defaults to Monday), and outputs [datetime] instances representing all days in that week.
function Get-DatesInWeekNumber {
param(
[Parameter(Mandatory)]
[int] $WeekNumber,
[int] $Year = (Get-Date).Year,
[DayOfWeek] $FirstDayOfWeek = 'Monday'
)
$date = [Globalization.ISOWeek]::ToDateTime($Year, $WeekNumber, $FirstDayOfWeek)
0..6 | ForEach-Object { $date.AddDays($_) }
}
Note the use of the [datetime] type's .AddDays() method.
Sample call, which formats the [datetime] instances as desired:
Get-DatesInWeekNumber -WeekNumber 1 -Year 2022 |
ForEach-Object ToString MM-dd-yyyy
This produces the output as shown in your question.

Writing Foldernames in a Array Powershell

I would like to write the directory names of several folders in an array. However, only all directory names with a date <today should be read. The directory names contain a date in this form * YYYYMMDD *
So I would have to do the following:
Borrow the date
Write the date in the form of YYYYMMDD in a variable
Read out directory names and check against the variable
Write data to an array ... do something ...
Can someone tell me how I can solve this with Powershell please?
Thank you
Start by retrieving all the candidate directories, then use Where-Object to extract the date part and test that it describes a date prior to today:
# Define threshold
$Today = (Get-Date).Date
# Go through all candidate directories
$oldDirectories = Get-ChildItem .\path\to\root\folder -Directory |Where-Object {
$dt = 0
# Test if directory name contains 8 consecutive digits describing a valid date
if($_.Name -match '(\d{8})' -and [datetime]::TryParseExact($Matches[1], 'yyyyMMdd', , $null, 'None', [ref]$dt)){
# We only want the ones with a date prior to today
$dt.Date -lt $today
}
else{
# Not containing a properly formatted date, we're not interested
$false
}
}
# Now we can extract the names
$oldDirectoryNames = #($oldDirectories.Name) # or #($oldDirectories |Select -Expand Name)
Do these directorynames start with the date?
yes
What do you mean by Borrow the date? Is that the date of today or what?
Determine the Date, Yes of today.
I read out the date accordingly and wrote it in a variable:
$Timestamp = ([datetime]::now).tostring("yyyyMMdd")
Now I want to read out all directory names which have got a Date < 1 Day and would like to process it in a foreach for further processing
Understandable?

compare line to string variable in powershell

I have txt file with date value, line by line
I try to compare them to today date in powershell but its not working
$DateTimeNow = (Get-Date).ToString('dd/MM/yyyy')
$data2 = get-content "output.txt"
$z= #()
foreach($line2 in $data2)
{
if($line2 -match $DateTimeNow){
write-host "same date"
}
}
the compare with "match" not work, I have try -eq and = but nothing better.
Have you any idea what I am doing wrong ?
The input dates all use 2-digit notation for the year (20 for 2020), but your string representing today's date uses 4-digits. Change to the appropriate format and it will work:
$DateTimeNow = Get-Date -Format 'dd/MM/yy'

Powershell keep looping until condition is true then proceed

I have written a script that so far is able to check a file "latest.json" for the "created_at" object which shows the last date that a commit has occurred for software.
$websiteJson = Invoke-WebRequest "https://website/latest.json" | ConvertFrom-Json | select created_at
$todaysDate = Get-Date -Format "yyyy-MM-dd HH:mm"
if($websitejson.created_at | where {$_.created_at -eq $todaysDate}){
Write-Output "Today's date matches"
} else {
Write-Output "has not yet been updated"
}
How part of latest.json looks like
"created_at":"2020-03-23 17:32:48"
How do I change this to keep looping until the date pull from latest.json matches then proceed to next step (would download and install software). Also, since "created at" has "17:32:48" will this cause the date check to fail since the time does not match?
. I want it to keep checking if dates match.
Thank you!
Right now, I'm not going to bother converting dates to match to make sure they're the same format, but what you need for your specific questions is just a do until loop. I might update this to check the date formats if you supply an example layout of the returned JSON.
Do{
$websiteJson = Invoke-WebRequest "https://website/latest.json" | ConvertFrom-Json | select created_at
$todaysDate = Get-Date -Format "yyyy-MM-dd HH:mm"
if($websitejson.created_at | where {$_.created_at -eq $todaysDate}){
Write-Output "Today's date matches"
} else {
Write-Output "has not yet been updated"
}
start-sleep -s 60
}until($websiteJson -eq $todaysDate)
I believe this wont work right off the bat. You'll have to get the JSON date and $todaysDate to be the same format, then you can do this and it will work.
if you want to compare the date and/or time, use datetime objects instead of datetime strings. something like this ...
if you want to test for the actual time difference between two time objects ...
((Get-Date -Date '2020-03-23 18:11:22') - [datetime]'2020-03-23 17:32:48').TotalHours
# result = 0.642777777777778
you keep mentioning date as if you don't want the time, so this method would work for comparing the date parts of two timestamps ...
# the date at the time the code was run = 2020 April 03, Friday 4:30:34 PM
$Today = (Get-Date).Date
$Created_At = '2020-04-03 15:15:15'
$Today -eq ([datetime]$Created_At).Date
result = True

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