Copy Active Directory User Account with Powershell - powershell

I'm building a script to create AD user account based from a CSV (nothing special so far ;o). One particular paramter I'd like to add is "copy from xxx" whereby the new account will be a copy from an existing account (just like the "copy account" option in the AD Console.
Can this be achieved? How?

This seems straightforward enough. Make a column in the CSV called "CopyFromAccount" or something.
Then, during the Import-CSV | Foreach loop throw an if / else statement in.
If ($_.CopyFromAccount -ne $null) {
... insert code to copy AD account here ...
}
Else {
... insert code to use other parameters on this line to create the account ...
}
There are several available examples on the internet for copying users in PowerShell. Here's an example using the Quest AD cmdlets: http://dmitrysotnikov.wordpress.com/2008/01/10/copy-ad-accounts-with-powershell/
To use the New-ADUser cmdlet from Microsoft instead of Quest, check out the instance parameter. More information is available in Get-Help or at the following URL: http://technet.microsoft.com/en-us/library/ee617253.aspx
It "Specifies an instance of a user object to use as a template for a new user object."
And is used like so:
$userInstance = Get-ADUser -Identity "saraDavis"
New-ADUser -SAMAccountName "ellenAdams" -Instance $userInstance -DisplayName "EllenAdams"

Related

Add in Active Directory security groups automatically using PowerShell

I have built an onboarding Powershell script to help our IT team simplify onboarding process. Script will add in some necessary AD fields, assign a mailbox and add in Security groups. After creating user, I have following code to add in user's officephone, street address and so on, those are based on which office they are going work in -
switch ($Office){
'office 1'{
// add in officephone and other fields
$Code = "O1"
}
'office 2'{
// add in officephone and other fields
$Code = "O2"
}
}
The $Code is used to assign Security groups as some SG names are based on office name. For example, if the user's role is maintenance officer in office O1, then a SG named MaintenanceOfficer_O1 needs to be added to this user. So the code looks like following -
Switch ($Role){
'Maintenance Officer'{
Add-ADGroupMember -Identity ("MaintenanceOffice_{0}" -f $Code) -Members $SAN
}
}
The script works fine, but we have quite a lot of roles and new roles will be created in future, so I was thinking to create some text files for our IT Support so they can add in more roles themselves. It will be something like -
get-content -path .\$role
// do a foreach loop for add-adgroupmember
Then in $role.txt file, there are AD groups for this role. So our IT support will be able to add in text file to the folder without needing access to script.
But you can see there is a problem as some SG group name requires $code.....
This is more like a logical problem than a technical one, please share any thoughts or let me know if you are confused with anything.
Thanks,
Raeb
Make your text file of roles a CSV file with two fields. The second field contains true or false to indicate if $code needs to be appended to the group name.
Edit 1:
If you want to keep the file simple you could test for the existence of the group as it appears in the file and if it doesn't exist test for the existence of the group with the variable appended.

Groups Not Being Given

Introduction
I've been tasked with creating a user management PowerShell script to be used for one of our customers so that we can easily manage users and automate a lot of our user creation processes.
The Issue
Our customer is insisting on using login scripts over GPO for mapping drives for users. I have added a login script builder to the script, however I cannot for the life of me figure out how to specify which drives actually need adding to the login script.
How Drive Mappings Are Managed
The way drive mappings are managed at our customer's network, is based on job role + Active Directory groups. They request on an E-Form which drives need to be mapped, and we then look through the Active Directory to see which group has permissions to access the requested drives. We then add these groups.
What I Need Help With
I've managed to figure out what code I need to use, however groups aren't being added to the user at all. I can't get it working.
Current Code
Note: This may not all be in order, there may be code in-between on the actual script. This is just relevant code.
Group Assignment
$GroupAssignment = $zzeveryone,$safebootdu,$infosecdrive,$mgmtboarddrive,$anaestheticsdrive,
$adverseirdrive,$breastcancersecsdrive,$bookwisedrive,$patientassessmentdrive,
$clinicaleducationdrive,$clinicaldevdrive,$clinicalauddrive,$CDUdrive,
$CBLettersdrive,$commsdrive,$colorectalscdrive,$colorectaldrive,
$codingdrive,$clinicalsupportdrive,$clinicalstddrive,$dietitiansdrive,
$dermatologydrive,$csudrive,$complaintsdrive,$entdrive,$emudrive,
$ElderlyCaredrive,$dischargedrive,$financedrive,$familyplanningdrive,
$GeneralSurgdrive,$gastrodrive,$infectiondrive,$infoptdrive,
$InfoMangtdrive,$MedStaffingdrive,$MedPhotodrive,$legaldrive,
$MedicalEquipdrive,$orthopticsdrive,$Orthopaedicsdrive,$OccHealthdrive,
$palsdrive,$Pharmacydrive,$Pathologydrive,$PostGraddrive,
$Podiatrydrive,$Respiratorydrive
Add-ADPrincipalGroupMembership -Identity $SAMAccountName -MemberOf $GroupAssignment
Example Group Assignment
$wcservicesdrive = if ($User.'Drives (Seperate with a ;)' -Contains 'women and childrens servicesdomain w&c services') {
Write-Output "domain w&c services"
}
Else {
Write-Output ""
}
$GroupAssignment should cause this to output to the Add-ADPrincipalGroupMembership, however it doesn't.
Any ideas?

outdated ACL on folders with powershell

I use Powershell to pull in data about user accounts, some of which includes details about an user's home folder.
I have been using get-item on folders to get the ACL to make sure an user has proper access to their home folder.
An example of my code is:
((get-item C:\exampleFolder).GetAccessControl('access')).Access
This provided me the list I needed and works great. However, if an user's username changes, it can take some time (like 5- 10 minutes) before Powershell can see the change even though viewing the folder's properties reflects the changes nearly instantaneously.
I am just seeing if there is a better way to pull the ACL data so that what I see in folder property page is what Powershell gets.
first world issue for me really, just trying to make my code a little bit more efficient.
Edit: This is a change in a username on a domain though Active Directory, not a username on a local machine.
There is the Get-ACL Cmdlet. This will output an object with an Access property listing all users with Access and their Access Level.
If you want to, you could use this to make a function to get more explicit data like this:
function Get-Permissions ($folder) {
(get-acl $folder).access | select `
#{Label="Identity";Expression={$_.IdentityReference}}, `
#{Label="Right";Expression={$_.FileSystemRights}}, `
#{Label="Access";Expression={$_.AccessControlType}}, `
#{Label="Inherited";Expression={$_.IsInherited}}, `
#{Label="Inheritance Flags";Expression={$_.InheritanceFlags}}, `
#{Label="Propagation Flags";Expression={$_.PropagationFlags}}
}
This you could easily pipe on to a | Format-Table -Auto or however you wish to visually consume your output.

AddAccessRule: "Some or all identity references could not be translated." How can I check a specific server?

With most ActiveDirectory commands, you can add a parameter: -server. This parameter has proven to be extremely useful to me, since where I am working seems to have some kind of slow updating system, and when I don't only use one of the servers, my programs can lag and completely bug.
I'm also trying to modify the ACL of a folder. To do this, I have a function that takes the -PassThru of a New-ADGroup command, and then pipes this into a custom function.
The custom function creates and returns new AccessRules (which are added to array $AccessRules), which are then added to an $acl variable:
$AccessRules |
%{$acl.AddAccessRule($_)}
This inconsistently returns errors: Sometimes, it runs smoothly, but other times, it returns the classic "Some or all identity references could not be translated". I am 90% sure this comes from the fact that it is not checking the right server, because even between
Get-ADGroup -filter {name -eq "[group name]"}
and
Get-ADGroup -filter {name -eq "[group name]"} -Server [server name/address]
I only get results for the second.
Is there a way I could add a similar -Server Parameter to something like .AddAccessRule()? Perhaps a slightly different method?
You can use a neat trick specified in this answer. You create a New-PSDrive to your AD using a certain server, then you call cd or set-location to that drive, voila, any .NET functions called (and any cmdlets that are not otherwise redirected to a different server) will use that server to process the requests, resolve AD entities into SIDs, etc, without you waiting for AD replication.

How to add ForeignSecurityPrincipals to AD LDS? Bringing 'AD users and computer accounts' to AD LDS as FSP?

How to add ForeignSecurityPrincipals to 'Active Directory Lightweight Directory Services' (AD LDS)? i.e. bringing 'AD security principals (users as well as computer accounts)' to AD LDS? Any script/ps cmdlet/tool?
Adding 'AD' security princials as "ForeingSecurtyPrincipals" to AD LDS using 'ADSI edit'
I know I can bring them by making them members of administrators/readers/users (i.e. in order to define roles for the 'AD users' as readers/users/administrators the foreign security principals need to be added - which makes sense - so ADSI edit is automatically adding the SIDs to foregin security principals container) (please see the attached image
Question (what are different ways of doing it other than assigning roles using adsi edit):
But, I am wondering is there a way without making the security principal as member of one of the roles? especially I don't want to do this way for 'computer accounts' - as they are not categorized as 'administrators' or 'users' or 'roles' - default in AD LDS schema. I think I can extend the schema so that my AD LDS instance understands computer accounts and then add the computers there.
Just curious if there is another way to do it? any other tool or PS script will also do as well as I am pretty sure there are number of 'directory services admin tools'
Regards.
You seem to be asking about two different things, here. The image is showing you grant access to Active Directory security principals to ADLDS. But then you start talking about extending the schema, suggesting you're looking to import objects from AD.
If it's the latter, you could use FIM, ADAMSync or roll your own using e.g. PowerShell.
More help on ADAMSync here
* UPDATE *
According to Dmitri Gavrilov in this post, manually adding FSPs is not possible.
Alternatively, you can use powershell to add the user/computer to one of the built-in groups (my example will use Readers), then immediately remove them. The foreignSecurityPrincipal will remain in the directory. It seems that ADAM/ADLDS is the one actually creating the foreignSecurityPrincipal object on your behalf when you request adding a member by SID.
Get the Readers group in the Configuration partition...
$servername = "myserver:389"
$configPartition = (Get-ADRootDSE -Server $servername).namingContexts | ? { $_ -match "^CN=Configuration" }
$readersGroup = ("CN=Readers,CN=Roles," + $configPartition)
Add the SID (Wrap in <SID=...>) to the Readers group
Set-ADObject -Identity $readersGroup-Add #{member = "<SID=S-X-X-XX-XXXXXXXXXX-XXXXXXXXXX-XXXXXXX-XXXXX>"} -Server $servername
Remove the SID from the Readers group
Set-ADObject -Identity $readersGroup-Remove #{member = "<SID=S-X-X-XX-XXXXXXXXXX-XXXXXXXXXX-XXXXXXX-XXXXX>"} -Server $servername
Actually it simply turned out to be that I can set 'permissions' on ad lds directory objects without adding to the 'ForeignSecuritypPrincipals' container...
So, I just set 'perms' based on sid (few examples are below, http://greatit.wordpress.com/2012/08/13/dsacls-and-built-in-groups/ )
Examples which grant 'generic all/full control' on AD LDS obect:
dscals "\\{myadldsserver}:{port}\cn=testadldsobect,cn=test,cn=com' /g {sid}:GA
dsacls {DN} /g {domain}/{username}:GA
dsacls {DN} /g {domain}/{machinename}$:GA
Regards.