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"
}
Related
I am working on automating tests a DumpSec report that runs a few logical tests and displays the solution. The DumpSec is a CSV file that I use ConvertFrom-Csv and then pull dates out of each user's field. However, I need to cast the date as DateTime so that I can compare multiple DateTime fields together properly.
Casting date time works and returns the correct answers on the first "If statement" but doesn't work on the second or third "if statements" even though I'm using the same casted variable DateTime as the first.
The error I'm getting is "Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime.""
$PasswordExpiresDateFormat = [datetime]::ParseExact($person.P
Function AutomateCSVFileFunction($DumpSecFilePath)
{
#Variable to store the path of the passed file path
$ImportedFile = Get-Content -LiteralPath $DumpSecFilePath | Select-Object -skip 1 | ConvertFrom-Csv
#Variables for dates to do the correct math
$ThirtyDays = (Get-Date).AddDays(-30)
$SixMonthsAgo = (Get-Date).AddDays(-180)
$Message = "How often does the organizations user's change their password? (Enter number of days): "
$Title = "Organization's Password Age Limit"
$PasswordAgeLimitDays = [Microsoft.VisualBasic.Interaction]::InputBox($Message, $Title)
#Arrays for information to be stored
$DisabledAccounts = #()
$LastLogonAccounts = #()
$NeverExpireAccounts = #()
$AccountsWherePasswordsNotRequired = #()
$PasswordLastChangedGreaterThanAgeLimit = #()
#For each loop to check disabled accounts greater than 6 months, 30 days inactive, accounts without an expiration date, accounts where passwords do not expire, and
foreach ($person in $ImportedFile)
{
$LastLogonDateFormat = [datetime]::ParseExact(($person.LastLogonTime).trim(), "MM/dd/yyyy HH:mm", $null)
$PasswordLastSetDateFormat = [datetime]::ParseExact($person.PswdLastSetTime, "MM/dd/yyyy HH:mm", $null)
$PasswordExpiresDateFormat = [datetime]::ParseExact($person.PswdExpiresTime, "MM/dd/yyyy HH:mm", $null)
#If statement checking each row for a disabled account greater than 6 months
if ((($LastLogonDateFormat -lt $SixMonthsAgo) -and ($person.AcctDisabled -contains "Yes")) -or ($LastLogonDateFormat -contains "Never"))
{
#Add persons info to array
$DisabledAccounts += $person
}
#If statement checking to see enabled accounts who haven't logged on in more than 30 days
if (($LastLogonDateFormat -gt $ThirtyDays) -and ($person.AcctDisabled -like "No"))
{
#Add persons info to array
$LastLogonAccounts += $person
}
}
I've tried casting using only [DateTime]$VariableName, but that doesn't work either. Using the .Trim() method doesn't work either.
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'
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.
This question already has answers here:
Compare Get-Date to Date as String
(1 answer)
How to parse (French) full month into datetime object in PowerShell?
(1 answer)
Closed 4 years ago.
$Deldate = "19-06-2018"
$Newdate = "04-06-2018"
I need to check which date is bigger.
if ($Deldate -ge $NewDate) {
write-host "NewDate is bigger"
}
else {
write-host "Deldate is bigger"
}
This is not working for me, and it looks like the format is not "System.DateTime". I'm getting the date values are from an external CSV file. How do I find a solution for this?
You should be able to cast the strings that you have created to the "datetime" type like so:
$Deldate = "19-06-2018"
$Newdate = "04-06-2018"
$Deldate = [datetime]::ParseExact("$Deldate", 'dd-MM-yyyy', $null)
$Newdate = [datetime]::ParseExact("$Newdate", 'dd-MM-yyyy', $null)
if ($Deldate -ge $NewDate) {
write-output "NewDate is bigger than or equal to"
}
else {
write-output "Deldate is bigger"
}
This returns the correct result. You can't simply use the Get-Date cmdlet, since the -Date required parameter also requires that the parameter be of type "DateTime", so you first have to cast the strings to the DateTime type.
Originally Proposed...
I am going to change the format of your date just a hair from DD-MM-YYYY to MM-DD-YYYY:
$Deldate = Get-Date "06-19-2018"
$Newdate = Get-Date "06-04-2018"
if ($Deldate -gt $Newdate) {
'Deldate is larger'
}
else {
'Newdate is larger or equal'
}
I'm creating two date objects based on the respective dates you gave. I'm comparing the two objects; PowerShell knows how to do the date math.
It works fine for U.S. style dates.
After much discussion...
However, for non-US style dates, consider calling datetime's constructor:
$Deldate = New-object 'datetime' -ArgumentList 2018, 6, 19, $null, $null, $null
$Newdate = New-object 'datetime' -ArgumentList 2018, 6, 4, $null, $null, $null
if ($Deldate -gt $Newdate) { 'Deldate is larger' } else { 'Newdate is larger or equal' }
Or, as proposed the [datetime]::ParseExact() method; documented here.
PowerShell is good with dates; it just has to know it's a date...
$Deldate = get-date "19-06-2018"
$Newdate = get-date "04-06-2018"
if ($Deldate -ge $NewDate) {
write-host "NewDate is bigger"
}
else {
write-host "Deldate is bigger"
}
Note: You could cast [datetime]$Deldate ="19-06-2018", but as explained in comments to PowerTip: Convert String into DateTime Object, it's valid only for US date format.
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)