How to switch to another domain and get-aduser - powershell

I am on a server under the DomainA. I can use Get-ADUser and it's working fine.
Now there is a trust built between DomainA and DomainB. I would like to switch to DomainB and get all the users that's in OU=New Users, DC=DomainB, DC=com.
I tried these but I get an error.
$FetchDomainB = Get-ADUser -SearchBase "OU=New Users, DC=DomainB, DC=com"
This asks me for Filter and i put in emailadress then it throws an error saying "Supplied distinguished name below to dc=DomainA,dc=net"
Same error is thrown for following code as well.
PS C:\> $test = Get-ADUser -SearchBase "dc=DomainB,dc=com" -filter {EmailAddress -like "*Smith_Karla*"} -Properties EmailAddress

Try specifying a DC in DomainB using the -Server property. Ex:
Get-ADUser -Server "dc01.DomainB.local" -Filter {EmailAddress -like "*Smith_Karla*"} -Properties EmailAddress

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress

get-aduser -Server "servername" -Identity %username% -Properties *
get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *
These work when you have the username. Also less to type than using the -filter property.
EDIT: Formatting.

best solution TNX to Drew Chapin and all of you too:
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
my script:
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } ` -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv

You can try in multiple domains one after another using below script:
Here, first we check whether user is present in a domain and if so, we get the email address. Else we check in the subsequent domain.
$users = Get-Content D:\UserBase\users.txt
foreach($user in $users)
{
if([bool] (Get-ADUser -Filter { SamAccountName -eq $user } -Server DomainA.com))
{
Get-ADUser -Filter { SamAccountName -eq $user } -Server DomainA.com -Properties Mail |Select-Object -ExpandProperty Mail | Out-file D:\UserBase\emails.txt -Append
}
elseif([bool] (Get-ADUser -Filter { SamAccountName -eq $user } -Server DomainB.com))
{
Get-ADUser -Filter { SamAccountName -eq $user } -Server DomainB.com -Properties Mail |Select-Object -ExpandProperty Mail | Out-file D:\UserBase\emails.txt -Append
}
Also, you can get the list of domains in the organization using below script:
$ForestObj = Get-ADForest -Server $env:USERDOMAIN
foreach($Domain in $ForestObj.Domains) {
Get-ADDomainController -Filter * -Server $Domain | select Domain,HostName,Site
}

Related

Copy groups from one user to another in Active Directory

I'm trying to run this PowerShell script that I found but it's not working for me and I'm getting an error could someone else check it and tell me if there is an issue here?
$CopyFromUser = Get-ADUser userName -Server domainName -Properties MemberOf
$CopyToUser = Get-ADUser userName -Server domainName -Properties MemberOf
$CopyFromUser.MemberOf | Where{$CopyToUser.MemberOf -notcontains $_} | Add-ADGroupMember -Members $CopyToUser
pause
This is the error that I'm getting.
| A positional parameter cannot be found that accepts argument
| 'Microsoft.ActiveDirectory.Management.ADPropertyValueCollection'.
Add the group memberships one at a time, explicitly pass the target DN to the -Identity parameter:
$CopyFromUser = Get-ADUser userName -Server domainName -Properties MemberOf
$CopyToUser = Get-ADUser userName -Server domainName -Properties MemberOf
$CopyFromUser.MemberOf |Where-Object {$CopyToUser.MemberOf -notcontains $_} |ForEach-Object {
Add-ADGroupMember -Identity $_ -Members $CopyToUser
}

Set-ADUser -Manager entity with Contact

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)"}
}
}

Organizing Active Directory accounts

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.

Custom Object multiple lines

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.

Update Active Directory "mail" attribute via PowerShell

I'm trying to update the email address listed in AD for all the users in a particular OU. This is the powershell script I'm using, but it's not working properly
Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase "OU=OtherOU,OU=SomeOu,DC=Domain,DC=local" | Set-ADUser -email $_.samaccountname#domain.com
I think it's because $_.samaccountname isn't returning anything when I try to do Set-ADUser.
Can anyone point me in the right direction for fixing this? Thanks!
Create a csv file with SamAccountName & email address
"SamAccountName","EmailAddress"
"john","john#xyz.com"
step 1: import to a variable
$users = Import-Csv .\email.csv
step 2: Call the variable
foreach ($user in $users) {
Set-ADUser -Identity $user.SamAccountName -EmailAddress $user.EmailAddress
}
In the current context $_ is null. You need to use Foreach-Object in order for $_ to be available.
Get-ADUser -Filter * ... | Foreach-Object{
Set-ADUser -Identity $_ -Email "$($_.samaccountname)#domain.com"
}
I suspect you'll need to use a subexpression for that:
"$($_.samaccountname)#domain.com"
Assuming username is domain\user1 or user1#domain.com
$user = "user1"
Set-ADUser $user -emailaddress "firtname.lastname#xyz.com"
Get-ADUser -Identity $user -Properties emailaddress
Get-ADUser -Filter * -SearchScope Subtree -SearchBase "OU=OUName,DC=domain,DC=com" |
Foreach-Object { Set-ADUser -Identity $_ -Email "$($_.samaccountname)#domain.com" }
This is from:
https://social.technet.microsoft.com/wiki/contents/articles/33311.powershell-update-mail-and-mailnickname-for-all-users-in-ou.aspx