I have an issue with Active Directory.
This is the scenario:
I have to perform some queries on a user set.
I have no access to graphical tool, only to Power Shell.
Those users are listed on a csv, one per row.
For those user, I have not the SamAccountName, but Name field, so their names and surnames.
So, I have to give this set as input to my queries.
I searched on google and I found this link, which has been very useful for most basic queries:
http://woshub.com/get-aduser-getting-active-directory-users-data-via-powershell/
Here, more or less at half page, I found something which seems usefull for me:
Task: for the list of accounts that are stored in a text file (one
account per line), you need to get the user’s company name from AD and
save it to a CSV file (you can easily import this file into Excel).
Import-Csv c:\ps\users_list.csv | ForEach {
Get-ADUser -identity $_.user -Properties Name, Company |
Select Name, Company |
Export-CSV c:\ps\users_ad_list.csv -Append -Encoding UTF8
}
So, I tried to convert this query for my needs. For Example, I don't need the company, but UserPrincipalName and SamAccountname.
The point is that when I perform the query, I got an error on -Identity parameter:
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null or an element of the argument collection contains a null value.
So, I searched again on google but I didin't found a solution; I catch only that the problem is related with use of $_.users variable.
So, I have 2 questions:
What is the problem with the above code?
Many examples I found work giving as input file a list of SamAccountName. In case the list is filled with other value, like mines, should I change something in the code?
EDIT: as requested, I share with you few rows of my csv.The name are of course changed for security and privacy reason.
Mickey Mouse
Donald Duck
Scrooge McDuck
And so on. So, the column is filled with name and surname of people.
I wonder: may be a problem the use of this syntax on other fields?
I mean, the name and surname couple is used not only for Name field in my case, but also for other 2 fields: DisplayName and another one I don't remember exactely. May be this the root cause?
Solved thanks to #Mathias R. Jessen. Is suggestion is valid: due I have a file whit a single column filled qith name and surname,
Get-Content C:\ps\users_list.csv |ForEach-Object { Get-ADUser -LDAPFilter "(ANR=$_)"
is a valid Syntax.
Related
my apologies if this has been asked many times before but I could use a hand with the command below. I am extracting Active Directory user information to a CSV but can use a hand with the correct code to replace the telePhoneNumber field with a fixed number of "555-555-5555" if it is null. I guess our organization has a lot of users without a phone number, and when I try to use the csv for our intended project, I can't because it errors and fails to grab the user if they do not have a phone number supplied. Is this possible to do?
Get-ADGroupMember -Identity "GROUPNAME" | Get-ADUser -Properties * | select #{N='UserName';E={$_.UserPrincipalName}},#{N='FirstName';E={"" + $_.givenName}},#{N='LastName';E={"" + $_.sn}},#{N='BusPhone';E={$_.telePhoneNumber}} | Export-csv c:\intel\thegroup.csv -NoTypeInformation
You can do whatever you like in the expression block of a calculated property.
Try changing:
#{N='BusPhone';E={$_.telePhoneNumber}}
to:
#{N='BusPhone';E={if($_.telePhoneNumber){$_.telePhoneNumber}else{'555-555-5555'}}}
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.
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
Good Morning Everyone,
I have a list of users (about 200 samAccountName's) and the only field that needs to be updated in AD is the telephoneNumber field. Example user John Smith Telephone number is 44444 and needs to be changed to 12345. Im guessing the csv file would contain a column for samAccountName, and the 2nd column would be telephoneNumber which would be a list of the numbers that are going to overwrite whatever the users current number is in AD.
i was thinking i could use the script from #Henrik Stanley Mortensen and modify it, but not sure what fields to change. THis is the url from my 1st question....
How to edit only the Firstname (givenName) of multiple users and import with csv
First let me say I agree stack is not a code generation site. It goes a long way if you have a little bit of code to show as to what you have tried. Even if it is TERRIBLE others in the community will feel compassion and empathy towards you versus negativity. Second please go to amazon and buy the book "Learn Powershell in a Month of Lunches" This will help you a ton and get your fundamentals down. Real easy read.
https://www.amazon.com/Learn-Windows-PowerShell-Month-Lunches/dp/1617294160/ref=sr_1_3?ie=UTF8&qid=1533311287&sr=8-3&keywords=powershell+books
Ok now off my soapbox. So I have created a csv called updatetelphones.csv and placed it in my C:\temp folder on my desktop. It has two columns one called SamAccountName and a second Called TelephoneNumber. Notice no spaces. With powershell we want to import that into a variable then iterate through each item and set the phone number for the user.
$UsersToUpdate = import-csv -Path "C:\temp\updatetelephones.csv"
foreach($User in $UsersToUpdate)
{
Set-ADUser -Identity $User.SamAccountName -OfficePhone $User.TelephoneNumber -WhatIf
}
Above is the powershell code. Now look carefully at the end of my set-aduser command I have a -whatif. ANYTIME you are making changes to AD I recommend you test your script with the -whatif first. That simulates the changes but doesn't make any so you can confirm it is accurate. So use this to test on your side. Once you validate remove the "-whatif" and run to actually make the changes. Peace and Happy powershell learning!!
it is strange, I use telephonenumber as a Get-ADUser property but OfficePhone as a parameter to set the telephonenumber property
Set-AdUser -Identity $user.SID -Credential $credential -OfficePhone $vp_telephonenumber -Server DC2.abc.com
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