Search code examples
powershellstring-to-datetime

Trying to compare extensionAttribute (string) to DateTime in PowerShell


I'm currently writing a PowerShell script that automatically Enable/Disable new hires in my company.

The situation today is that when HR recruit new employee he added automatically to AD with his starting date in extension attribute in this format - dd/MM/yyyy. I need the script to run every day and if the starting date equal today then make this user Enable and if not and the user somehow is enable to change it back to disable (sometime IT guys enabling new users in order to do some setup for them and forget to disable it).

This is my non-working script, any idea what's wrong?

Import-Module ActiveDirectory 

$currentDate = Get-Date -Format "dd/MM/yyyy"
$startingDate = [datetime]::parseexact($startingDate, 'dd/MM/yyyy', $null)
$startingDate = ([datetime]$user.extensionAttribute2)
$SearchBase = "DC=DC,DC=DC"
$NewHires = Get-ADUser -SearchBase $SearchBase -Properties extensionAttribute2 -Filter {(extensionAttribute2 -like '*')}

foreach ($User in $NewHires) {
try {
if ($startingDate -eq $currentDate) {
  Set-ADUser -Identity $User.SamAccountName -Enabled $true
}
else {
if($startingDate -gt $currentDate) {
  Set-ADUser -Identity $User.SamAccountName -Enabled $false
}}
} catch { Write-Output Out-File $User.SamAccountName has bad value in attribute | -Filepath $logpath -Append
}} 

Solution

  • There are a few issues with your script.

    1.)

    You are comparing a string and a DateTime.

    Get-Date returns a string if -Format is specified. Omit that switch, just use Get-Date, so both $currentData and $startingDate are DateTime. Also, use the Date property to get only the date component.

    2.)

    Your loop seems to be in the wrong place. Put the datetime parsing into the loop.

    3.)

    The way you do your file output is not correct. See my updated version.

    Also, some suggestions for improvement:

    • It's best to not depend on try/catch to check if the value is valid. You can use TryParseExact.
    • Use the pipeline and ForEach-Object, to streamline your script

    Updated script:

    Import-Module ActiveDirectory 
    $currentDate = (Get-Date).Date
    [dateTime]$startingDate = 0
    $SearchBase = "DC=DC,DC=DC"
    Get-ADUser -SearchBase $SearchBase -Properties extensionAttribute2 -Filter {(extensionAttribute2 -like '*')} | ForEach-Object {
        if ([datetime]::TryParseExact($_.extensionAttribute2, 'dd/MM/yyyy', $null, 'None', [ref]$startingDate)) {
            if ($startingDate -eq $currentDate) {
              Set-ADUser -Identity $_.SamAccountName -Enabled $true
            }
            elseif($startingDate -gt $currentDate) {
              Set-ADUser -Identity $_.SamAccountName -Enabled $false
            }
        }
        else {
            "$($_.SamAccountName) has bad value in attribute" | Out-File $logpath -Append
        }
    }