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'
Related
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
I created a small scrip that have do to a couple of thinks.
get string from description field from user in specific container
take part of this string (substring method) that holds date information
convert this string to date format
compare this formated string with a current date - 30 days and do sth
The problem is that comparing is not working correctly. I tried do recognise date that is older than 30 days and do something but i see that comparison not always work. sometimes it does not recognize that date is less then - 30 days from current day
Script below
$DateMaxTime = (Get-date).AddDays(-30)
$DateFormatMaxTime = Get-Date $DateMaxTime -Format dd/MM/yyyy
$getData = get-ADUser -Filter * -Properties * -SearchBase "OU=Disabled,OU=Control,OU=x,OU=x,DC=x,DC=x,DC=x" `
|where {$_.Description -like "LEFT*"} |select name,samaccountname,description
Foreach ($Data IN $getData){
$DataPart = $null
$DataPart=$Data.description
$DatePart= $DataPart.substring(5,10)
$FinalDate = [datetime]::ParseExact($DatePart,'dd/MM/yyyy',$null)
$FinalDateFormat = Get-Date $FinalDate -Format dd/MM/yyyy
If ($FinalDateFormat -lt $DateFormatMaxTime ){ Write-Host "$($Data.samaccountname), $($Data.description) moved to deleteMe" }
else{ Write-Host "$($Data.samaccountname), $($Data.description) still in disabled" }
}
Below output shows me the wrong results (as example i did it for one user - >
Based on this logic the value $FinalDateFormat that hold date -> 31-12-2018 is less then value $DateFormatMaxTime that hold this date -> 25-06-2019 but it still applies else statement ...
I am not sure why, i did something wrong with date conversion ?
I put the comments as the answer:
I would compare the datetime versions of the dates rather than the string versions.
If ($FinalDate -lt $DateMaxTime)
Running
get-date -format
makes them strings.
$finaldate.gettype(); $datemaxtime.gettype()
shows the types. They are [datetime], not [string] like the other two.
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.
I am currently trying to convert a date from the one displayed in regedit to a readable datetime format. But I do not know how to do this, I'm working with the following:
.GetValue('InstallDate')
And in the .csv file, it display it as this: 20150914
How would I go about converting that into a readable date?
try
[datetime]::Parseexact("20150914","yyyyMMdd", $null )
I'm not sure why you down voted the other answer because he is right on the money with [Datetime]::ParseExact you will have to deal with the null values though
$Regbase = Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\
foreach ($entry in $regBase)
{
$date = (Get-ItemProperty HKLM:\$entry | select installdate).installdate
try
{
[DateTime]::ParseExact($date, "yyyyMMdd", [CultureInfo]::InvariantCulture)
}
catch [exception]
{
"Date Value: $date"
}
}
PowerShell Date is just .NET DateTime. Check DateTime.ParseExact.
[DateTime]::ParseExact("20151010", "yyyyMMdd", [CultureInfo]::InvariantCulture)
I have a requirement where I need to read a date from a CSV file and compare it to a date variable within the script. However, my code doesn't work when some of the date entries in the CSV file are blank. Any idea how I can store a blank date in [datetime] variable?
Here's the part of my code:
#This is my date variable in script
$InactivityDate = (Get-Date).AddDays(-62).Date
Import-Csv $MyCSV | ForEach {
#This is the date variable i'm reading from csv file
$whenCreated = $_.whenCreated
#This converts value in string variable $whenCreated to [DateTime] format
$ConvertWhenCreated = ([datetime]::ParseExact($whenCreated,"dd/MM/yyyy",$null))
#Comparing dates
if($ConvertWhenCreated -le $InactivityDate)
{
"Account is dormant"
}
Above code works fine when $whenCreated contains some value, but when it's blank PowerShell obviously cannot compare a date variable with blank value :(
The only solution I can see now is to check if $whenCreated is blank and save a very old date like it happens in Excel, e.g.:
if($whenCreated -eq "")
{
$whenCreated = "01/01/1900 00:00:00"
}
Should this be OK or is there another logical solution?
Your problem most likely isn't with the comparison, but with the conversion of the blank value to a date via ParseExact(). If you want accounts with no date treated as dormant you could simply do something like this:
$whenCreated = $_.whenCreated
if ($whenCreated) {
$whenCreated = [DateTime]::ParseExact($whenCreated, 'dd/MM/yyyy', $null)
}
if ($whenCreated -le $InactivityDate) {
'Account is dormant'
}
Checking if an empty string (or $null) is lesser or equal to $InactivityDate will return $true as long as $InactivityDate contains a date.
You already test if the string is empty, which is good. But there is no need to assign a fake old date, you can simply assign $null:
$InactivityDate = (Get-Date).AddDays(-62)
$dateString = "2014-11-01"
if ($dateString) {
$date = Get-Date $dateString
} else {
$date = $null
}
if ($date -le $InactivityDate) {
"Account is dormant"
}