How to change ManagedBy owner from one user to another one for 150+ groups using power shell - powershell

I would like to change the Active Directory Group tab ManagedBy user to another one. With PowerShell script, I exported the groups with the old owner (>150) to a csv file. Now I need to change the owner of those groups using the csv file as input.
I don`t have much experience with scripting, I appreciate any help.
Thanks!

The task is very easy with PowerShell. You didn't show an example of the CSV data you exported so an example may not be exact. However, I assume you exported the default output of Get-ADGroup it might look something like this
(Import-Csv C:\temp\managedBy.csv).DistinguishedName| Set-ADGroup -ManagedBy <NewManager's DN>
Note: I like to use the DistinguishedName for these things but samAccountName should also work.
(Import-Csv C:\temp\managedBy.csv).samAccountName | Set-ADGroup -ManagedBy <NewsamAccountName>
Note: Again with the assumption that your Csv data is a direct export Get-ADGroups's output. You cannot pipe Import-Csv directly to Get/Set-ADGroup as the latter will have trouble determining which property to bind to the -Identity parameter.
However, I would point out you really don't need the intermediate Csv file. You can query AD directly for groups managed by the old manager and pipe that to a command to change the owner.
Get-ADGroup -Filter "ManagedBy -eq '<OldOwner'sDN>'" |
Set-ADGroup -ManagedBy "<NewOwner'sDN"
Note: Again you may be able to get away with using the samAccountName instead of the DN.
Note: You can add the WhatIf parameter to the Set-ADGroup` command to preview what will happen before actually running it.

Related

Adding multiple users to multiple OU's using a single line powershell command

I am very new to PowerShell and I have a .csv file that contains 100 different users with the fields Name,Surname,Section and depending on the section the user has to be created in that specific OU. Ex:Joe,Heart,Accounts - When I execute the command I the user has to be created in the Accounts Organizational Unit.
The biggest challenge is that I have to use only a 1 line command to create the 100 users in their respective OU. I tried multiple commands and watched numerous videos but none seem to work. I am working on Windows Server 2012.
Currently, I am trying to make use of this command
Import-Csv C:\Users\Administrator\Desktop\HomeList.csv
| ForEach-Object { Set-ADOrganizationalUnit -Identity $_.Section -Member $_.Name }
And I am getting the error
A parameter cannot be found that matches parameter name 'Member'
Since this is a school exercise I don't think it would be a good thing to give you a working piece of code to simply copy/paste.
I can however give you tips on where to look..
The CSV file has these fields as you say: Name, Surname, Section where
'Name' seems to be the users first name
'SurName' is the users last name
'Section' is the (display)name of the OU
Each user in the CSV must be moved to the specified OU and for that purpose the ActiveDirectory module has the cmdlet Move-ADObject, so you iterate through the data with a Foreach-Object {...}
There are several issues to deal with here.
The first one is that the Move-ADObject cmdlet takes an -Identity parameter that can either be a DistinghuishedName or a GUID. You can also pipe an ADUser object to it.
In your CSV you have the users first name (AD property GivenName) and the users last name (property SurName) and so you will need to get the user object from AD first in order to be able to use Move-ADObject.
For that, there are several answers to be found on the internet, both using the -Filter aswell as the -LDAPFilter parameters of Get-ADUser.
The second issue is that Move-ADObject needs a -TargetPath parameter in the form of a DistinghuishedName and since your CSV file only contains the (Display)Name of the target OU, you need to get that first too.
The cmdlet for that is Get-ADOrganizationalUnit where you can use the -Filter parameter, something like this: -Filter "Name -eq '$($_.Section)'"
Note: you can also use Get-ADObject and filter on "ObjectClass -eq 'organizationalunit'" as an alternative for Get-ADOrganizationalUnit, but that is a bit more difficult.
Once you have both AD objects, you're all set to use the Move-ADObject cmdlet to move the user to the target OU, but always add the -WhatIf switch to the command when trying out your code. Only if you are satisfied with the results shown in the console, you can take that switch off.
Please do not attempt to put all this in a single line. Write it out and add comments to the code. If you got it working you may want to look at speeding things up a little by organising the data from the CSV using Group-Object
Hope this helps

Get Memberships Of User

I have a very simple question but for some reason I can't seem to get my head around it.
I need a line of code that could be ran as a user from a client and lists all the "memeber of" groups from the AD (ONLY FOR THIS CURRENT USER). similar to
Get-ADGroupMember -identity "domain admins" -Recursive | foreach{ get-aduser $_} | select SamAccountName,objectclass,name
I would like the result to be listed.
I either need a way to import the AD module on a client computer or another way to contact the DC and get the users current "memeber of" groups.
/Niklas
I found the best way for my needs but CB.'s answer worked as well!
[ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.memberof -replace '^CN=([^,]+).+$','$1'
I can then keep using this output in my code
you can use dos command line:
net user /domain %username%
The easiest way to do this would be with
Get-ADPrincipalGroupMembership -identity "Username"
Now this also means that you would have to have the active directory module loaded which you can find more information on its use on Technet Get-ADPrincipalGroupMember
If you simply want to produce a list, make a call to the command prompt as I find this works well, although it does truncate group names:
net user %username% /DOMAIN
If you want to programmatically get them and easily do something with that data, you'll want to rely on the Active Directory cmdlets.
To determine if you have these readily available in Powershell, you'll need to run the following command:
Get-Module –ListAvailable
If you don't see ActiveDirectory in the list you will need to first download and install the Windows Management Framework and import the module yourself:
Import-Module ActiveDirectory
Once that's done I believe this command should do the trick:
(Get-ADUser userName –Properties MemberOf | Select-Object MemberOf).MemberOf
Hopefully that gets you started. I'm fairly certain that there's more than one way to accomplish this with Powershell. Take a look at the Microsoft TechNet documentation to see if you can find something that better suits your needs.
Personally I have only ever needed to query AD group memberships ad-hoc for diagnostic purposes and have always relied on Get-ADUser or the command line call, depending on the target audience of the resulting data.

Powershell Query AD to export emails of all users in .txt file?

I would like to write a PS script that exports a .csv for all users that are specified in a separate .txt file. So, for instance, I could create a text file that has
Timmy Turner
Silly Sally
Then, when the script is ran, it searches AD for those two users and exports a CSV with their first name, last name, and email address.
I originally got hung up a bit on how the "Get-ADUser" filter worked, but I produced something semi-usable. However, what I've come up with just asks who you are searching for and then uses that. I think it would be much easier to just have it reference a pre-made text file, especially when searching for a large number of users. Or, there may be an even easier way to do this that I am not thinking of. Here is what I currently have:
$SamAc = Read-Host 'What is the first and last name of the person you would like to search for?'
$filter = "sAmAccountname -eq ""$SamAc"""
Get-ADUser -Filter $filter -Properties FirstName, LastName, EmailAddress | select FirstName, LastName, EmailAddress | Export-CSV "C:\Scripts\PS_ADQuery\Email_Addresses.csv"
I feel like the "Get-Content" cmdlet is close to what I am looking for, but I can't seem to get it to function correctly. I may be going in the totally wrong direction, though.
I found the answer. It turns out I even had the AD properties totally wrong. Take my comments with a grain of salt since I may not fully understand the processes behind each line of code, but this does exactly what I was looking to do.
#creates a $users variable for each username listed in the users.txt file. the ForEach
#command allows you to loop through each item in the users.txt array. the scriptblock
#nested into the ForEach command queries each username for specific properties.
$users = ForEach ($user in $(Get-Content C:\Scripts\PS_ADQuery\users.txt)) {
Get-AdUser $user -Properties GivenName,sn,mail
}
#takes the $users variable defined by the ForEach command and exports listed properties
#to a csv format.
$users |
Select-Object GivenName,sn,mail |
Export-CSV -Path C:\Scripts\PS_ADQuery\output.csv -NoTypeInformation

Import Member Group attribute from AD to .csv

I am using ActiveRoles Management Shell under Windows XP , Powershell ver 2 for retreiving Group data from AD and exporting it to csv file.Everything works well apart from getting member list it is so long that the program is writing in excel cells under member column System.String[] each time.How can I make it write whole list there , is it possible ? I could actually have only the name of the member don't need whole connection path.Is there a possibility to get from group field member only name ?
get-QADGroup -SearchRoot 'ou=User,ou=Groups,ou=PL,dc=test,dc=com'| Select-Object -property name,sAMAccountName,description,groupType,member|Export-Csv -path Y:\csv\groups.csv
Ok, as Matt suggested you want an expression in your Select statement. I would use something like this:
#{l="Members";e={$_.Members -join ", "}}
Which when inserted into your one-liner looks like:
get-QADGroup -SearchRoot 'ou=User,ou=Groups,ou=PL,dc=test,dc=com'| Select-Object -property name,sAMAccountName,description,groupType,#{l='Members';e={$_.member -join ", "}}|Export-Csv -path Y:\csv\groups.csv -NoTypeInfo
I also added -NoTypeInfo to the export to skip the annoying lead line telling you it's a PSCustomObject or some such and actually just get your data (and headers).
I don't have access to the quest cmdlets so I will provide a solution based on cmdlets from the activedirectory
Get-ADUser -Filter * -SearchBase "OU=Employees,DC=Domain,DC=Local" -Properties memberof |
Select-Object name,#{Name="Groups";Expression={$_.MemberOf |
ForEach-Object{(Get-ADGroup -Identity $_).Name + ";"}}} |
Export-Csv C:\temp\TEST.CSV -Append
To make sense of this by line:
Should be self explanatory. Get all users in the OU defined. You would need to change this to suit your needs.
The select statement appears normal until you reach the calculated property Groups.
What continues from the previous line is cycling through every group that an individual user is a memberof and get the friendly name of the group (MemberOf returns DistinguishedName's). At the end of every group add a ";" as to not interfere with the CSV that will be made later.
Append to a csv file.
For brevity I didnt include all the extra properties that you included in your Select-Object statement. You would obviously need to add those back as the need fits.
Since you have the use the Quest cmdlets you could just change member in your select statement to the following:
#{Name="Groups";Expression={$_.member | ForEach-Object{"$_;"}}}
I cannot test if this will work. It is based on the assumption that member contains a simple name as supposed to a distinguishedname

PowerShell: Compare CSV to AD

I'm fairly new to PowerShell and I'm posting this on many forums but I've had success with programming assistance from here before and although this isn't strictly programming, I was hoping someone might know the answer.
My organization had about 5,300 users we needed to disable for a client. Someone decided the best use of our time was have people go through AD and disable them one at a time. Soon as I got wind of this I put a stop to it and used PowerShell to take the CSV list we already had, and ran a cmdlet to disable all of the users in the CSV list.
This appeared to work, but I wanted to run a comparison. I want to compare the users from the CSV file, to the users in AD, and confirm that they are all disabled without having to check all 5300 individually. We checked about 60 random ones to verify my run worked, but I want to make sure none slipped through the cracks.
I've tried a couple scripts and I've tried some variations of cmdlets. None of the scripts I tried even worked, spammed with errors. When I try to run a search of AD either using get-content or import-CSV from the csv file, when I export its giving me about 7600 disabled users (if I search by disabled). There were only 5300 users in total, so it must be giving me all of the disabled users in AD. Other cmdlets i've run appear to do the same thing, its exporting an entire AD list instead of just comparing against my CSV file.
Any assistance anyone can provide would be helpful.
Without knowing the exact structure of your CSV I'm going to assuming it is as such:
"CN=","OU=","DC="
"JSmith","Accounting","Foo.com"
"BAnderson","HR","Foo.com"
"JAustin","IT","Foo.com"
That said, if your first field actually has CN= included (i.e. "CN=JSmith","OU=Accounting","Foo.com") you will want to trim that with .TrimStart("CN=").
$ToRemove = Import-CSV UserList.csv
$UserList=#()
ForEach($User in $ToRemove){
$Temp = ""|Select "User","Disabled"
$Temp.User = $User.'CN='
If((Get-aduser $Temp.User -Prop Enabled).Enabled){$Temp.Disabled='False'}else{$Temp.Disabled='True'}
$UserList+=$Temp}
$UserList|?{$_.Disabled -eq 'False'}
That loads the CSV into a variable, runs each listing through a loop that checks the 'CN=' property, creates a custom object for each user containing just their name and if they are disabled, and then adds that object to an array for ease of use later. In the end you are left with $UserList that lists everybody in the original CSV and if they are disabled. You can output it to a file, filter it for just those that are still enabled, or whatever you want. As noted before if your CSV actually has CN=JSmith for each line you will want to update line 5 to look as such:
$Temp.User = $User.'CN='.TrimStart("CN=")
If you don't have any headers in the CSV file you may want to inject them. Just put a line at the top that looks like:
CN=,OU=,DC=
Or, if you have varying OU depths you may be better off doing a GC and then running each line through a split, taking the first part, trimming the CN= off the beginning, and checking to see if they are disabled like:
GC SomeFile.CSV||%{$_.split(",")[0].trimstart("CN=")|%{If((get-aduser $_ -prop enabled).enabled){"$_ is Enabled"}else{"$_ is Disabled"}}}
Assuming your CSV has a column called DN you can run the following which will return all users from your spreadsheet which are enabled
import-csv YourUsersCSV.csv | Get-ADUser -Filter
{DistinguishedName -eq $_.DN } |
where{$_.enabled -eq $true} |
Select-Object -Property DistinguishedName,samaccountname,enabled