Home > OS >  If statement in powershell with -lt value for date does not calculate properly for years?
If statement in powershell with -lt value for date does not calculate properly for years?

Time:12-25

I've been using this script for about a year now and it seems any values with the year as 22 are not getting treated as greater than the current year of 21... am I not formatting properly? The csv file is just a username,MM/DD/YY format. The specific part of the script that is not working due to dates being next year is: if($today -lt $EndDate)... seems to work for months and days comparatively, but not for years?

In my test file I have one user who has a date of 01/03/22 and the script says the date has ended (meaning $today is not less than the $enddate value, when it is actually next year)

Any pointers?

$Import_csv = Import-Csv -Path "C:\temp\namesanddates.csv"

# Get today's date
$today = Get-Date -format MM/dd/yy

# Begin import csv process

$Import_csv | ForEach-Object {

    # Retrieve DN of User
    $UserDN = (Get-ADUser -Identity $_.Name).distinguishedName
    
    # Error check missing date - set to tomorrow
    $EndDate = (Get-Date).AddDays(1).ToString("MM/dd/yy")
    # Try to use date entered from file
    $EndDate   = (Get-Date $_.date).toString("MM/dd/yy")

    Write-Host "Current User:" $UserDN
    Write-Host "End Date in file:" $EndDate

if($today -lt $EndDate){
    Write-Host "User affected:" $UserDN
    Write-Host "Moving Accounts....." $UserDN

}else{
    Write-Output "User account date ended for:" $UserDN
    }
} 
Write-Host "Script Complete"

CodePudding user response:

As Others Mentioned, the problem here is that you compare date object ($today) with string ($EndDate )

you need to modify it as follow

Import_csv = Import-Csv -Path "C:\temp\namesanddates.csv"

# Get today's date
$today = Get-Date -format MM/dd/yy

# Begin import csv process
$Import_csv | ForEach-Object {

# Retrieve DN of User
$UserDN = (Get-ADUser -Identity $_.Name).distinguishedName

# use date entered from file
EndDate   = Get-Date $_.date

Write-Host "Current User:" $UserDN
Write-Host "End Date in file: $($EndDate.toString("MM/dd/yy"))"

if($today -lt $EndDate){
    Write-Host "User affected:" $UserDN
    Write-Host "Moving Accounts....." $UserDN
}
else{
    Write-Output "User account date ended for:" $UserDN
    }
} 
Write-Host "Script Complete"

CodePudding user response:

Taken as strings, it makes sense. One thing to do is have the left side be a datetime type in the comparison, and the right side will get converted automatically.

$today = Get-Date  # 12/24/21
$today | % gettype

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     DateTime                                 System.ValueType


$today -lt '01/03/22'

True

Usually people use date strings like this, which can be sorted:

Get-Date -format yyyy/MM/dd

2021/12/24
  • Related