A script that sends emails via the OUTLOOK SMTP server

I got a task to do a script in PowerShell where I need to get out of AD a list of names that begin with the letter “A” with full name, username and creation date criteria. Then export the list with custom headers and export it to a CSV file Then import the CSV file again and output anyone who works over two years (full name) So far I have done the script correctly in my opinion because it works. Now I’m pretty stuck I need to make every user on the list who went out first to make a folder (no matter where) and give full permissions to the folder - I did something but it seems to be incorrect. Then I need to send an email with a table that states the full name and folder path and that the sender will be no@reply.com.

The code I wrote:

 Get-ADUser -filter * -SearchBase "OU=meitavdash,OU=Users,DC=meitav,DC=co,DC=il"

    Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} |Format-Table name,SamAccountName,whenCreated

    Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} | Select-Object @{n='FullName';e={$_.Name}},@{n='UserName';e={$_.SamaccountName}},@{n='CreateDate';e={$_.WhenCreated}} |  export-csv -path c:\userexport.csv
    Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} | where {$_.whencreated -le (Get-Date).AddYears(-2)}|Select-Object @{n='FullName';e={$_.Name}} 

    $sp=$((Get-Date).AddDays(-365*2)); Get-ADUser -Properties whenCreated -Filter {name -like "A*" -and whenCreated -ge $sp}|%{New-Item -Path "c:\temp" -ItemType Directory; icacls "c:\temp" /T /grant "$($_.samaccountname):(OI)(CI)F"

No need to search Active Directory multiple times. Search AD once then put results into a variable.

# Check AD one time for users
$user = Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} -SearchBase "OU=meitavdash,OU=Users,DC=meitav,DC=co,DC=il" | 
Select-Object name,samaccountname,whencreated

# Export list with custom headers
$user | ConvertTo-Csv | ConvertFrom-Csv -Header FullName,UserName,CreateDate |
Select-Object -Skip 1 | Export-Csv -NoTypeInformation -Path .\user.csv

# List two year employees
$user2 = Import-Csv .\user.csv | 
Where-Object {$_.CreateDate -ge (get-date).AddYears(-2)}

# Create temp folder for each user
$list = [System.Collections.ArrayList]@()
Import-Csv .\user.csv | ForEach-Object {
    New-Item -Path "C:\Temp\$($_.UserName)" -ItemType Directory
    icacls "C:\Temp\$($_.UserName)" /T /grant "$($_.UserName):(OI)(CI)F"
    $obj=[PSCustomObject]@{Name=$_.FullName ; Path="C:\Temp\$($_.UserName)"}
    $list.Add($obj) | Out-Null
}

# Set email properties
    $prop = @{
        From = 'no@reply.com'
        To = 'sender@mail.com'
        Subject = 'User Path List'
        Body = $list
        SmtpServer = 'your.smtp.server.com'
    }

Send-MailMessage @prop