I created a script to pull some info from AD, the problem I'm having is the Secondary SMTP address field has more then one line. I'd like to show each secondary SMTP in a new line. My Script output looks like {smtp:joe.rodriguez#con...
$searchBase = 'OU=Users,DC=Contoso,DC=LOCAL'
$users = Get-ADUser -filter 'enabled -eq $true' -SearchBase $searchBase |select -expand samaccountname
Foreach ($user in $users){
$Secondary = get-recipient -Identity $user -ErrorAction SilentlyContinue| select Name -ExpandProperty emailaddresses |? {$_.Prefix -like "SMTP" -and $_.IsPrimaryAddress -like "False"} |select -ExpandProperty $_.Smtpaddress
New-Object -TypeName PSCustomObject -Property #{
Name = Get-ADUser -Identity $user -Properties DisplayName |select -ExpandProperty DisplayName
"Login ID" = Get-ADUser -Identity $user -Properties SamAccountName |select -ExpandProperty SamAccountName
Primary = get-recipient -Identity $user -ErrorAction SilentlyContinue| select Name -ExpandProperty emailaddresses |? {$_.Prefix -like "SMTP" -and $_.IsPrimaryAddress -like "True"} |select -ExpandProperty Smtpaddress
Secondary = $Secondary
}
}
Personally I'd make an array, pull your user list, and then iterate through the secondary SMTP addresses for each user adding your custom object to the array for each entry.
$Userlist = #()
$searchBase = 'OU=Users,DC=Contoso,DC=LOCAL'
$users = Get-ADUser -filter 'enabled -eq $true' -SearchBase $searchBase -Properties DisplayName
Foreach ($user in $users){
$Recip = get-recipient -Identity $user.samaccountname -ErrorAction SilentlyContinue| select Name -ExpandProperty emailaddresses |? {$_.Prefix -like "SMTP"}
$Recip|? {$_.IsPrimaryAddress -like "False"} |select -ExpandProperty Smtpaddress |%{
$UserList += New-Object -TypeName PSCustomObject -Property #{
Name = $User.DisplayName
"Login ID" = $User.SamAccountName
Primary = $Recip|? {$_.IsPrimaryAddress -like "True"} |select -ExpandProperty Smtpaddress
Secondary = $_
}
}
}
This script (based off your script above) also reduces the number of server queries by 3 per user I think, so it should run a ton faster.
Related
I have a csv with the following fields:
User | AD_Manager_ID | Dyn_Manager_ID
abc#mydomain.com | 1234 | 1455
The Dyn_Manager_ID field is the employeeID of another user.
99% of the time it corresponds to an actual user, but sometimes it corresponds to a contact
I can get the contact like this:
Get-ADObject -Filter "employeeID -eq '1455'"
but when I try to Set-ADUser -Manager with that object, it returns a 'Cannot find an object with idenity" error.
Here is the code for regular users (non contacts):
$csvimport = import-csv -Path C:\Users\ME\Desktop\AccountChangesCSV.csv
foreach ($User in $csvimport)
{
Get-aduser -filter "employeeID -eq '$($user.DYN_Mgr_ID)'" | select-object samaccountname -
OutVariable ManagersName
Get-ADUser -Filter "employeeID -eq '$($user.AD_ID)'" | set-aduser -Manager
$ManagersName.samaccountname
}
If someone's manager could be either another user or a contact, then do not use Get-ADUser to find the manager object, but Get-ADObject instead.
If this was a contact, there is no SamAccountName property, but instead, you can use the DistinguishedName or the ObjectGUID
Try
$csvimport = Import-Csv -Path 'C:\Users\ME\Desktop\AccountChangesCSV.csv'
foreach ($user in $csvimport) {
$manager = Get-ADObject -Filter "employeeID -eq '$($user.DYN_Mgr_ID)'" -ErrorAction SilentlyContinue
if ($manager) {
# now update the users Manager property with the DistinguishedName of the manager object
Get-ADUser -Filter "employeeID -eq '$($user.AD_ID)'" |
Set-ADUser -Manager $manager.DistinguishedName # or ObjectGUID instead of DistinguishedName
}
}
This works for both AD user objects and contacts alike
I think this post has the answer: updating an ADUser's Manager with a contact card
This is the code that finally worked for me:
$csvimport = Import-Csv -Path 'C:\Users\ME\Desktop\AccountChangesCSV.csv'
foreach ($user in $csvimport) {
$manager = Get-ADObject -Filter "employeeID -eq '$($user.DYN_Mgr_ID)'" -
ErrorAction SilentlyContinue
if ($manager) {
# now update the users Manager property with the DistinguishedName of the
manager object
$aduser = Get-ADUser -Filter "employeeID -eq '$($user.AD_ID)'"
Set-AdUser -Identity $aduser.SamAccountName -replace
#{manager="$($manager.distinguishedname)"}
}
}
I'm looking to get the the Group Name, Managed By Name and Managed by Email in a PowerShell query similar to this.
Get-ADGroup -filter {Name -like "*Admins" }
The output would look something similar to:
Group Name | Managed By Name | Managed By Email
The issue I'm having is with joining Get-ADGroup and Get-ADUser. In SQL this "join" would happen on get-adgroup.managedby = get-aduser.distinguishedname. I know that's not how it works in Powershell, just thought I'd throw out an example of what I'm trying to do.
Any help would both be welcomed and appreciated.
I see #Mathias R. Jessen beat me to it, but here's what I had:
Get-ADGroup -filter {Name -like "*IT*" } -Properties managedBy |
ForEach-Object {
$managedBy = $_.managedBy;
if ($managedBy -ne $null)
{
$manager = (get-aduser -Identity $managedBy -Properties emailAddress);
$managerName = $manager.Name;
$managerEmail = $manager.emailAddress;
}
else
{
$managerName = 'N/A';
$managerEmail = 'N/A';
}
Write-Output $_; } |
Select-Object #{n='Group Name';e={$_.Name}}, #{n='Managed By Name';e={$managerName}}, #{n='Managed By Email';e={$managerEmail}}
You can do it like this:
$Groups = Get-ADGroup -Filter { Name -like "*Admins" } -Properties managedBy,mail
$Groups |Select-Object Name,#{Name='ManagedBy';Expression={(Get-ADUser $_.managedBy).Name}},Mail
The #{} syntax after Select-Object is known as a calculated property.
You could also pipe the groups to ForEach-Object and call Get-ADUser inside the process scriptblock:
Get-ADGroup -Filter {Name -like "*Admins"} -Properties managedBy,mail |ForEach-Object {
# Find the managedBy user
$GroupManager = Get-ADUser -Identity $_.managedBy
# Create a new custom object based on the group properties + managedby user
New-Object psobject -Property #{
Name = $_.Name
ManagedBy = $GroupManager.Name
Email = $_.mail
}
}
I would something do like this:
# Get all groups into a variable
$Group = Get-ADGroup -Filter {Name -like "*Admin*"} | Select-Object -expandProperty Name
foreach ($Groups in $Group){
# Get ManagedBy name for each group (If ManagedBy is empty group wil not be listed)
$User = Get-ADGroup $Groups -Properties * | Select-Object -ExpandProperty ManagedBy
foreach ($Users in $User){
# Get Name and EmailAddress for each User
$Name = Get-ADUser $Users | Select-Object -ExpandProperty Name
$Email = Get-ADUser $Users -Properties * | Select-Object -ExpandProperty EmailAddress
# Write output
Write-Host $Groups "," $Name "," $Email
}
}
Hope this helps.
I am trying to get a script to work that will organize my active directory accounts based off of their display name since all of our accounts have their OU in their name (or a subOU). I am trying to do this with an If statement inside of a ForEach loop in PowerShell. Every time I run it though, it keeps asking me for an identity. Can anyone help me fix this? This is what I have...
Import-Module ActiveDirectory
$OU = "OU=Test, OU=com"
$Test1OU = "OU=Test1, OU=Test, OU=Com"
$Test2OU = "OU=Test2, OU=Test, OU=Com"
$Users = (Get-ADUser -SearchBase $OU -Filter * -Properties samAccountName,DisplayName)
ForEach ($user in $users)
{
If ($($user.DisplayName -like ("*Supply*" -or "*Supplies*"))
{Move-ADObject -Identity $($user.samAccountName -TargetPath $Test1OU}
ElseIf ($($user.DisplayName -like ("*Accounting*" -or "*Accountant*"))
{Move-AdObject -TargetPath $Test2OU}
}
You are running into a few problems here
Like Vesper said you are not passing anything to Move-ADObject hence the error you are getting
$DisplayNames is not a string array of names but an object with a displayname property. That is what -ExpandProperty parameter is for with Select-Object FYI.
You are pulling all the users but only really want to process certain ones. Instead of -Filter * lets use a more targeted approach.
While it is tempting you cant nest -like conditions like that. If you take "*Supply*" -or "*Supplies*" and type that it will evaluate to true. Same as all non zero length strings.
For what we plan on doing we will not have to address all those issues. We should use the pipeline to help with this. Depending on how many variances you have something like a switch statement might be better which is covered below.
$supplyFilter = 'DisplayName -like "*Supply*" -or DisplayName -like "*Supplies*"'
$accountFilter = 'DisplayName -like "*Accounting*" -or DisplayName -like "*Accountant*"'
Get-ADUser -SearchBase $OU -Filter $supplyFilter -Properties displayName | Move-ADObject -TargetPath $Test1OU
Get-ADUser -SearchBase $OU -Filter $accountFilter -Properties displayName | Move-ADObject -TargetPath $Test2OU
You could get freaky with this and make a custom object in a loop with filter and target pairs so that you don't need to repeat the cmdlet call to each Get-ADuser instance.
$moves = #(
#{
Filter = 'DisplayName -like "*Supply*" -or DisplayName -like "*Supplies*"'
OU = "OU=Test1, OU=Test, OU=Com"
},
#{
Filter = 'DisplayName -like "*Accounting*" -or DisplayName -like "*Accountant*"'
OU = "OU=Test2, OU=Test, OU=Com"
}
) | ForEach-Object{New-Object -TypeName PSCustomObject -Property $_}
ForEach($move in $moves){
Get-ADUser -SearchBase $OU -Filter $move.Filter -Properties displayName | Move-ADObject -TargetPath $move.OU
}
You should be able to scale into this easily by adding new $moves. This would be cleaner with PowerShell v3.0 but I do not know what version you have.
Using a switch
If you want something closer to what your currently have I would suggest something like this instead then.
$Users = Get-ADUser -SearchBase $OU -Filter * -Properties DisplayName
ForEach ($user in $users){
switch($user.DisplayName) {
($_ -like "*Supply*" -or $_ -like "*Supplies*"){Move-ADObject -Identity $user -TargetPath $Test1OU}
($_ -like "*Accounting*" -or $_ -like "*Accountant*"){Move-ADObject -Identity $user -TargetPath $Test1OU}
}
}
I'm not able to test currently, but this should do the trick:
Import-Module ActiveDirectory
$OU = "OU=Test, OU=com"
$Test1OU = "OU=Test1, OU=Test, OU=Com"
$Test2OU = "OU=Test2, OU=Test, OU=Com"
$users = (Get-ADUser -SearchBase $OU -Filter * -Properties displayName)
foreach ($user in $users)
{
if ($($user.displayName) -like "*Supply*" -OR $($user.displayName) -like "*Supplies*")){
Move-ADObject -Identity $user -TargetPath $Test1OU
}
elseif ($($user.displayName) -like "*Accounting*" -OR $($user.displayName) -like "*Accountant*")) {
Move-AdObject -Identity $user -TargetPath $Test2OU
}
}
I've Added an Identity Parameter to Move-ADObject also i've changed some of the var names to better reflect their content.
I have a list of users full name that I'd like to get their SAMaccount name but when I run my code I get no results. Anyone have any ideas?
$users = Get-Content C:\users\admin\Desktop\move.txt
foreach ($user in $users){
Get-ADUser -Filter {Name -eq "$user"} |Select-Object name, samaccountname
}
It could be that $user is null inside the script block. Try to use double quotes instead of braces and put the variable in single quotes to make the valid query (name contain spaces):
Get-ADUser -Filter "Name -eq '$user'" | Select-Object name, samaccountname
Here is a powershell script that should work for you. You'll want to go to the link to read the fine details, http://wbarena.com/2015/01/powershell-find-ad-user-full-name.html.
Import-Module ActiveDirectory
$aResults = #()
$List = Get-Content “.\List.txt”
ForEach($Item in $List){
$Item = $Item.Trim()
$User = Get-ADUser -Filter{displayName -like $Item -and SamAccountName -notlike “a-*” -and Enabled -eq $True} -Properties SamAccountName, GivenName, Surname, telephoneNumber, mail
$hItemDetails = New-Object -TypeName psobject -Property #{
FullName = $Item
UserName = $User.SamAccountName
Email = $User.mail
Tel = $User.telephoneNumber
}
#Add data to array
$aResults += $hItemDetails
}
$aResults | Export-CSV “.\Results.csv”
Use first and last name separately.
foreach ($user in $users){
$SplitName = -split $user
Get-ADUser -Filter {(GivenName -eq $SplitName[0]) -and (Surname -eq $splitName[1])} |Select-Object name, samaccountname
}
I have a requirement to generate a CSV report to get group members. However, I there are many child domains which contains groups starting with ADM.
I need report in the following format:
GroupName User Company LasLogon CN
ADM_AM UserOne CP1
I've found one script on internet:
Get-ADGroup -Server dc1.chd1.pd.local -Filter 'Name -like "ADM*"' |
ForEach-Object{
$hash=#{GroupName=$_.Name;Member=''}
$_ | Get-ADGroupMember -ea 0 -recurs |
ForEach-Object{
$hash.Member=$_.Name
New-Object psObject -Property $hash
}
} |
sort groupname,member
This script only gives me GroupName and UserName but not other information.
How can I generate this report?
I'm not sure what "ADM_AM, UserOne, CP1" is, but i got this much for you. I'm still new to powershell so forgive me if this is a lot of code =)
$array = #()
Foreach ($group in (Get-ADGroup -Server dc1.chd1.pd.local -Filter 'Name -like "ADM*"'))
{
$hash=#{Username ='';GroupName=$group.Name;Company='';LastLogon='';CN=''}
$members = $hash.GroupName | Get-ADGroupMember -Recursive -ErrorAction SilentlyContinue
Foreach($member in $members)
{
$properties = $member.SamAccountName | Get-ADUser -Properties SamAccountName, Company, lastLogon, CN
$hash.Username = $properties.SamAccountName
$hash.Company = $properties.Company
$hash.LastLogon = $properties.lastLogon
$hash.CN = $properties.CN
$obj = New-Object psObject -Property $hash
$array += $obj
}
}
$array | Export-Csv C:\ -NoTypeInformation
Here is what I would do, Im sure you can shorten it. You shoud specify a searchbase. Once you have the members samaccountname, you can use Get-ADUser to get whatever fields you want.
$GrpArr = #()
$Groups = get-adgroup -filter {name -like "adm*"} -searchbase "ou=Groups,dc=all,dc=ca" | select samaccountname
foreach ($group in $groups)
{
$GrpArr += $group
$members = get-adgroupmember $group | select samaccountName
foreach ($member in $members)
{
$memprops = get-aduser $member -properties company
$comp = $memprops.company
$grpArr += "$member,$comp"
}
}
$grpArr | export-csv c:\temp\Groups.csv -NoTypeInformation