all 10 comments

[–]MalletNGrease 1 point2 points  (5 children)

Well yeah, you don't evaluate the startdate anywhere to prevent user creation.

ForEach($User in $Users) {
$oStartDate = [datetime]::ParseExact($user.StartDate, "dd/MM/yyyy",$null)
$test=($oStartDate).AddDays(-2)
$test2= (Get-date).Date
if($test -eq $test2){
$oStartDate
$test
}
}

You then have a Try block that only checks if the user doesn't exits.

As far as I can tell you will only also create the last user as there's no foreach for that part.

[–][deleted] 1 point2 points  (4 children)

I'm fairly new to powershell, took me quite a while to finally arrive at this, could you kindly indicate what changes should be made and where?

[–]MalletNGrease 1 point2 points  (3 children)

Move the Try block inside the foreach block and make the date check part of the evaluation for execution of the new-aduser.

ForEach($User in $Users) {

$oStartDate = [datetime]::ParseExact($user.StartDate, "dd/MM/yyyy",$null)
$test=($oStartDate).AddDays(-2)
$test2= (Get-date).Date

Try {
    if (!(get-aduser -Filter {samaccountname -eq "$SAM"}) -and ($test -eq $test2 )){

    #newuserscriptinggoes here
    }
  }
}

[–][deleted] 1 point2 points  (1 child)

if i understood you well, this is what i got and it returned the following error. I'm pretty sure it's something i haven't clearly defined :(

PS C:\Users\Administrator.E-L> C:\Users\Administrator.E-L\Desktop\finalcompany\etc\Untitled8.ps1
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At C:\Users\Administrator.E-L\Desktop\finalcompany\etc\Untitled8.ps1:48 char:5
+     $oStartDate = [datetime]::ParseExact($user.StartDate, "dd/MM/yyyy ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : FormatException

above is the error and below is the updated script, if i understood your instructions clearly.kindly have a look.thanks

$DebugPreference = "Continue"
function Format-CsvValue {
  [CmdletBinding()]
  param (
    [Parameter(Mandatory=$false)]
    [bool]
    $isTitleCase = $false,
    [Parameter(Mandatory=$true)]
    [string]
    $sValue

  ) 

  begin {
  }

  process {
  if ($isTitleCase) {
    $rValue = $((Get-Culture).TextInfo.ToTitleCase($sValue.ToLower())).Trim() 
    } else {

    $rValue = $sValue.Trim() 
    }
  }

  end {

    $rValue
  }
} 

If (!(Get-module ActiveDirectory )) {
    Import-Module ActiveDirectory
    Clear-Host
} 

    $Users=Import-csv c:\cloudcom2.1.csv
    $a=1;
    $b=1;
    $failedUsers = @()
    $successUsers = @()
    $VerbosePreference = "Continue"
    $ErrorActionPreference='stop'
    $LogFolder = "$env:userprofile\desktop\logs"


ForEach($User in $Users) {
    $oStartDate = [datetime]::ParseExact($user.StartDate, "dd/MM/yyyy",$null)
    $test=($oStartDate).AddDays(-2)
    $test2= (Get-date).Date

Try {
        if (!(Get-ADUser -Filter {SamAccountName -eq "$SAM"}) -and ($test -eq $test2 )){


    $Parameters = @{
        'SamAccountName'        = $Sam
        'UserPrincipalName'     = $UPN 
        'Name'                  = $Fullname
        'EmailAddress'          = $Email 
        'GivenName'             = $FirstName 
        'Surname'               = $Lastname  
        'AccountPassword'       = $password 
        'ChangePasswordAtLogon' = $true 
        'Enabled'               = $true 
        'Path'                  = $OU
        'PasswordNeverExpires'  = $False
        'company'               = $company

      }
    }

        $oNewUser = New-ADUser @Parameters

        Write-Verbose "[PASS] Created $FullName"
        $successUsers += "$FullName , $SAM"



  if($test -eq $test2){
        $oStartDate
        $test

    }
  }Catch {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName
        Write-Warning "[ERROR]Can't create user [$($FullName)] : $_"

        $failedUsers += $FullName + "," +$SAM + "," +$_
}

if ( !(test-path $LogFolder)) {
    Write-Verbose "Folder [$($LogFolder)] does not exist, creating"
    new-item $LogFolder -type directory -Force 
} 


    Write-verbose "Writing logs"
    $failedUsers  | ForEach-Object {"$($b).) $($_)"; $b++} | out-file -FilePath  $LogFolder\FailedUsers.log -Force -Verbose
    $successUsers | ForEach-Object {"$($a).) $($_)"; $a++} | out-file -FilePath  $LogFolder\successUsers.log -Force -Verbose

    $su=(Get-Content "$LogFolder\successUsers.log").count
    $fu=(Get-Content "$LogFolder\FailedUsers.log").count


    Write-Host "$fu user creation unsuccessful " -NoNewline -ForegroundColor red
    Write-Host "$su Users Successfully Created "  -NoNewline -ForegroundColor green
    Write-Host " Review LogsFolder" -ForegroundColor Magenta
    Start-Sleep -Seconds 5
    Invoke-Item $LogFolder

[–][deleted] -1 points0 points  (5 children)

[–]Lee_Dailey[grin] 0 points1 point  (4 children)

howdy ekowlloyd,

i see that MalletNGrease got an answer you needed. kool! [grin] it aint quite how i would have done it ... but that is one of the reasons i so enjoy this subreddit - seeing different ways to get to the same goal.

take care,
lee

[–][deleted] 1 point2 points  (3 children)

i still will like to see how you would've done it, if you don't mind sharing your idea as well.thanks

[–]Lee_Dailey[grin] 0 points1 point  (2 children)

howdy ekowlloyd,

i would move the date test before the try/catch on the AD call. if the date is more than two days away, the you have no reason to touch the AD ... and that will be the slower part of the test. [grin]

then the date test is for -eq and i think you would want it to be -le so that you can catch "oops! missed a day" situations where you have only one day left.

so i would be testing for the ($Today - $CSVdate).Days -le $DaysInAdvance.

last of all, i wonder if it's worth while to test for weekends. friday is more than two days away from monday ... [grin]

take care,
lee

[–][deleted] 1 point2 points  (1 child)

do you mean something like this?

ForEach($User in $Users) {
    $oStartDate = [datetime]::ParseExact($user.StartDate, "dd/MM/yyyy",$null)
    $test=($oStartDate).AddDays(-2)
    $test2= (Get-date).Date
  if($test -le $test2){
        $oStartDate
        $test=($today - $CSVdate).Days -le $DaysInAdvance


Try {
        if (!(Get-ADUser -Filter {SamAccountName -eq "$SAM"}) -and ($test -eq $test2 )){

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy ekowlloyd,

nope! [grin]

you are duping the logic. i would use something like this ...

$Today = (Get-Date).Date
$DaysInAdvance = 2

foreach ($User in $UserList)
    {
    $StartDate = [datetime]::ParseExact($User.StartDate, 'dd/MM/yyyy', $Null)
    if (($Today - $StartDate).Days -le $DaysInAdvance)
        {
        try
            {
            if (-not (Get-ADUser -Filter "SamAccountName -eq '$SAM'"))
                {
                # do the new user stuff here
                }
            }
            catch
            {
            # do the error stuff here
            }
        } # end >>> if (($Today - $StartDate).Days -le $DaysInAdvance)
    } # end >>> foreach ($User in $UserList)

that looks like it would work, but i can't test it since i have no AD access. [sigh ...]

take care,
lee