A script that sends emails via the OUTLOOK SMTP server - powershell

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"

Send-MailMessage is your friend: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-7

As for this...
"my problem I do not know how to actually create a table with the full
name and folder path"
.. is this hat you are after?
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} |
%{
$PathUnc = (New-Item -Path 'c:\temp' -ItemType Directory).FullName
icacls 'c:\temp' /T /grant "$($_.samaccountname):(OI)(CI)F"
}

Related

powershell get-aduser query with two or more name variables

I'm tryin to get a powershell query with two displaynames in it. It works fine with one displayname.
Get-ADUser -Filter "displayName -like '**'" -SearchBase "OU= ,OU= ,OU= AG,DC= ,DC=" -Properties * | select-object mail | sort-object
How can i insert more displayname variables to the code?
You can use OR in the filter
Get-ADUser -Filter "DisplayName -like '*user1*' -or DisplayName -like '*user2*'" -SearchBase "OU= ,OU= ,OU= AG,DC= ,DC=" -Properties Mail |
Select-Object -ExpandProperty Mail | Sort-Object
Using LDAP Filter you can do like this (using | as OR)
Get-ADUser -LDAPFilter "(|(cn=*user1*)(cn=*user2*))" -SearchBase "OU= ,OU= ,OU= AG,DC= ,DC=" -Properties Mail |
Select-Object -ExpandProperty Mail | Sort-Object

get deactivated computers in ad from csv list

i'm tryin to figure out which computers are deactivated. for that i provide the computer names in a csv list. i just want to output the computers which are deactivated. this is what i have. unfortunately i get all deactivated computers. but i only want that names provided in the csv
Import-CSV -Path "C:\pc_names" | Select -expand Name | Get-ADComputer -searchbase 'XXX' -Filter {(Enabled -eq $False)} -Properties Name, OperatingSystem | Export-CSV “C:\Temp\DisabledComps.CSV” -NoTypeInformation
The problem is likely in the Get-ADComputer command, you specify a SearchBase (assumedly an OU), and a filter for all disabled computers - but never actually include the name of the PC that you piped in from the CSV, so it just returns every disabled PC under that search base.
Try something like this instead;
Import-CSV -Path "C:\pc_names" | Select -Expand Name | Get-ADComputer -SearchBase 'XXX' -Filter {(Enabled -eq $False) -and ($_.Name)} -Properties Name, OperatingSystem | Export-CSV "C:\Temp\DisabledComps.CSV" -NoTypeInformation
Note the $_.Name in the filter.
I've probably got that filter syntax wrong - but that should be the cause.
There is no way you can test if the computername is to be found in an array of names using the -Filter parameter..
You need to first collect computer objects within your SearchBase OU and filter the disabled ones only.
Following that, you filter out the ones that can be found in the $pcNames array using a Where-Object clause:
$pcNames = (Import-Csv -Path "C:\pc_names.csv").Name
Get-ADComputer -SearchBase 'XXX' -Filter "Enabled -eq 'False'" -Properties OperatingSystem |
Where-Object { $pcNames -contains $_.Name } | # or: Where-Object { $_.Name -in $pcNames }
Export-Csv -Path "C:\Temp\DisabledComps.csv" -NoTypeInformation
Note: Get-ADComputer by default already returns these properties: DistinguishedName, DNSHostName, Enabled, Name, ObjectClass, ObjectGUID, SamAccountName, SID, UserPrincipalName. That means you only have to ask for the extra property OperatingSystem in this case
It's pretty obvious that something like this ignores what's piped in and returns many computers.
'comp001' | get-adcomputer -filter 'Enabled -eq $False'
If you wait until the end, there is an error message:
get-adcomputer : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its
properties do not match any of the parameters that take pipeline input.
At line:1 char:13
+ 'comp001' | get-adcomputer -filter 'Enabled -eq $false'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (comp001:String) [Get-ADComputer], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
You can do get-adcomputer inside a foreach loop and test Name as well:
$list = echo comp001 comp002 comp003
$list | % { get-adcomputer -filter 'Enabled -eq $False -and Name -eq $_' }

collect samaccount powershell

I have a list of users in a CSV, but I need to collect the SamAccount attribute from each user by name in the ad.
CSV model
Script
Get-ADObject -Filter 'ObjectClass -eq "user" -and userAccountControl -eq "512"' -Properties * | Select-Object SamAccountName,CN,DisplayName, | Export-CSV -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
I'm a little lost I don't know how to do a foreach using name
I am trying but without success.
Trying to get samaccountname based on Name on csv file.
Import-Csv -Path C:\Temp\userteste.csv | foreach-Object {Get-ADUser -Filter {Name -like $_.name} -Properties Name | Select-Object samAccountName}
and export to csv file.
Why use Get-ADObject and not Get-ADUser for this? The latter gives you more of the desired properties you need in the CSV.
As aside, it is wasteful to do -Properties * if all you want is a small set of user attributes.
Something like this should work:
Get-ADUser -Filter "Enabled -eq $true" -Properties DisplayName, CN |
Select-Object SamAccountName, CN, DisplayName |
Export-Csv -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
As per your comment you need to get some extra attributes of the users listed in the CSV, you can do this:
Import-Csv -Path C:\Temp\userteste.csv | ForEach-Object {
Get-ADUser -Filter "Name -like '$($_.Name)'" -Properties DisplayName, CN |
Select-Object SamAccountName, CN, DisplayName
} | Export-Csv -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
Hope that helps

Piping output of get-ADUser to Get-ADGroup with an LDAP filter

I'm trying to stitch together two lines of PowerShell, but I just can't figure the syntax. There is a post that sounds like it might be what I need, but it isn't using -LDAPFilter.
To generate a list of AD users created in the last 100 days, I use
$now = ((Get-Date).AddDays(-100)).Date
$users = Get-ADUser -Filter {whenCreated -ge $now} -Searchbase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" |
Where-Object { $_.Enabled -eq 'True' }
And this code from "How to get ALL AD user groups (recursively) with Powershell or other tools?" does the next step, which is to find all the groups that a user is a member of:
$username = 'd.trump'
$dn = (Get-ADUser $username).DistinguishedName
Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn) |
select -Expand Name
but I can't pipe the output of the first into the second to get an overall list.
Get-ADUser -Filter {whenCreated -ge $now} -Searchbase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" |
Where-Object { $_.Enabled -eq 'True' } |
Select-Object DistinguishedName |
Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $_) |
select -expand Name
The error message is:
Get-ADGroup : The search filter cannot be recognized
I thought the second code snippet extracted the distingushed name and supplied it to the filter, and that is what I have tried to do in the pipeline.
You are missing ForEach-Object (alias %).
The following code should work:
Get-ADUser -Filter {whenCreated -ge $now} -SearchBase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" `
| Where-Object { $_.Enabled -eq 'True' } `
| %{Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $_.DistinguishedName)} `
| Select-Object -ExpandProperty Name
If you want to output both user and group information you can expand the code like this:
Get-ADUser -Filter {whenCreated -ge $now} -SearchBase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" `
| Where-Object { $_.Enabled -eq 'True' } `
| %{$group = Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $_.DistinguishedName);Write-Output $_.UserPrincipalName $group.Name}

Powershell - CSV - AD Attribute Update

I'm trying to get AD attributes updated with information from my payroll system. I have a good dump of employee information, and can get most things updated, but I'm having some small problems that hopefully someone much better with Powershell than I can assist with.
--- UpdateInfo.ps1 ---
Import-Module ActiveDirectory
$Users=Import-Csv C:\info_update.csv
foreach($u in $Users)
{
Get-ADUser -Filter "employeeID -eq '$($u.employeeID)'" -properties * | set-aduser -replace #{title="$($u.title)";extensionAttribute1="$($u.title)";givenName="$($u.givenName)";initials="$($u.initials)";middleName="$($u.middleName)";sn="$($u.sn)";physicalDeliveryOfficeName="$($u.physicalDeliveryOfficeName)";streetAddress="$($u.streetAddress)";l="$($u.l)";st="$($u.st)";co="$($u.co)";countryCode="$($u.countryCode)";c="$($u.c)";postalCode="$($u.postalCode)";department="$($u.department)"}
}
--- info_update.csv ---
employeeID,givenName,initials,middleName,sn,name,title,physicalDeliveryOfficeName,streetAddress,l,st,co,countryCode,c,postalCode,department,manager
"111","Smith","Q","Quincy","John","Smith, John Q.","Tech II","Springfield, IL","800 E Monroe St.","Springfield","IL","United States","840","US","62701","IT","540"
Two questions:
I can't get the 'name' field to update. I thought that it was because of the space, but the physicaldeliveryofficename has a space, too...and it's working fine.
I need to do a lookup for the manager ID (last column), return the DN of the manager, and use that to update the manager attribute.
If anyone can help, I would greatly appreciate it. I feel like I'm really close, but I'm overlooking something.
Thanks!
---UPDATE---
Thanks to #TheMadTechnician
Here's the final answer.
Import-Module ActiveDirectory
$Users=Import-Csv C:\Job_titles.csv
foreach($u in $Users)
{
$Mgr = Get-ADUser -Filter "employeeID -eq '$($u.manager)'" | Select -ExpandProperty DistinguishedName
Get-ADUser -Filter "employeeID -eq '$($u.employeeID)'" -properties * | set-aduser -replace #{title="$($u.title)";extensionAttribute1="$($u.title)";givenName="$($u.givenName)";displayName="$($u.name)";initials="$($u.initials)";middleName="$($u.middleName)";sn="$($u.sn)";physicalDeliveryOfficeName="$($u.physicalDeliveryOfficeName)";streetAddress="$($u.streetAddress)";l="$($u.l)";st="$($u.st)";co="$($u.co)";countryCode="$($u.countryCode)";c="$($u.c)";postalCode="$($u.postalCode)";department="$($u.department)";manager="$Mgr"} -PassThru | Rename-ADObject -NewName "$($u.name)"
}
So we will use get-aduser and filter on EmployeeID for the manager, and use Select -ExpandProperty for the DistinguishedName property. I also use the -PassThru switch on your Set-ADUser, and pipe it to Rename-ADObject. See how that suits you:
Import-Module ActiveDirectory
$Users=Import-Csv C:\info_update.csv
$Managers = Import-Csv C:\Managers.csv
foreach($u in $Users)
{
$Mgr = Get-ADUser -Filter "employeeID -eq '$($u.manager)'" | Select -ExpandProperty DistinguishedName
Get-ADUser -Filter "employeeID -eq '$($u.employeeID)'" -properties * | set-aduser -replace #{title="$($u.title)";extensionAttribute1="$($u.title)";givenName="$($u.givenName)";initials="$($u.initials)";middleName="$($u.middleName)";sn="$($u.sn)";physicalDeliveryOfficeName="$($u.physicalDeliveryOfficeName)";streetAddress="$($u.streetAddress)";l="$($u.l)";st="$($u.st)";co="$($u.co)";countryCode="$($u.countryCode)";c="$($u.c)";postalCode="$($u.postalCode)";department="$($u.department)";manager="$Mgr"} -PassThru | Rename-ADObject -NewName "$($u.name)"
}
Set-ADUser cannot be used to set Name. See http://technet.microsoft.com/en-us/library/ee617215.aspx
Try using Rename-ADObject:
Rename-ADObject [-Identity] <ADObject> [-NewName] <string>
Source: http://technet.microsoft.com/en-us/library/ee617225.aspx