Adding users to security group from CSV file using Display Name property - powershell

I've got this code from a post here, which works perfectly:
Import-CSV $file | % {$myGroup | Add-ADGroupMember -Members $_.Alias}
The first line of my CSV file is "alias" and every other line is a username. This works great.
However when I modify the code to this:
Import-CSV $file | % {$myGroup | Add-ADGroupMember -Members $_.displayName}
And I modify the CSV file first line to "displayName" and every other line to a display name, it doesn't work. I'm guessing this is because displayName is not a valid property for this code, so how can I modify this to use the display name of a user instead of the username?

That won't work because DisplayName is not an accepted value. Here's a list of valid values. See the cmdlet online help here: http://technet.microsoft.com/en-us/library/ee617210.aspx
Members
Specifies a set of user, group, and computer objects in a
comma-separated list to add to a group. To identify each object, use
one of the following property values. Note: The identifier in
parentheses is the LDAP display name.
Distinguished Name
Example: CN=SaraDavis,CN=Europe,CN=Users,DC=corp,DC=contoso,DC=com
GUID (objectGUID)
Example: 599c3d2e-f72d-4d20-8a88-030d99495f20
Security Identifier (objectSid)
Example: S-1-5-21-3165297888-301567370-576410423-1103
SAM Account Name (sAMAccountName)
Example: saradavis
In addition, the Members parameter accept a collection of values so you could also do this:
$members = Import-CSV $file | Foreach-Object {$_.Alias}
$myGroup | Add-ADGroupMember -Members $members

Related

Powershell Get-ADGroupMember does not return list

I am trying to utilize PowerShell to audit all of our security group members in AD. I have been trying to get Get-ADGroupMember to work but anytime I try it, it returns the message 'Cannot find an object with identity 'groupName' under: 'DC=xxxx,DC=xxxx,DC=xxxx,DC=xxxx'.
Ive tried the following with no luck:
$groupNames = 'groupName1' , 'groupName2' , 'groupName3'
foreach ($group in $groupNames) {
Get-AdGroupMember -Identity $group
}
Has anyone successfully compiled a list of group members in security groups from AD and exported them into a .CSV?
There are few things to consider when querying AD groups using the Get-AdGroup* commands.
The -Identity parameter only accepts values that match an object's Guid, ObjectSid, DistinguishedName, or SamAccountName. If your input is something other than one of those attribute values, you will either need to run another command to retrieve the proper data or change your list.
-Identity only accepts a single value, which means if you want to supply a list of values, you need to loop through them.
Get-AdGroupMember does not output as many attribute/value pairs as Get-AdUser. You cannot force it to output more attributes than it does. It does not have a -Properties parameter like Get-AdUser. Sometimes it requires using both commands to get all of the required data.
You can send Get-Ad* output to CSV using Export-Csv. If you do not use any property filtering like with Select-Object, the returned property names will be the columns of the CSV. The associated values of the properties will appear in rows with each row representing one returned object. You can choose to either send the entire results of the command once to the CSV or each time the command runs using Export-Csv -Append.
Use Select-Object to only output properties you care about. Select-Object Property outputs a custom object that includes only the property Property and the value(s) of Property for each object returned. If you only want to return the value rather than a custom object, you can use Select-Object -Expand Property.
Get-Content can be used to read a file. If the file contains only a list of values, perhaps SamAccountName values, you can use Get-Content file.txt to retrieve that list. The list will be an array that can be looped through.
Since Get-AdUser can be verbose, it is wise to use the -Properties parameter to explicitly list any extra properties beyond the default set you want to return. -Properties * will return all properties, but that is not best practice.
Given the above considerations, I would do the following:
$groupNames = 'groupName1' , 'groupName2' , 'groupName3'
# Alternatively, if you have a file (file.txt) with your group names listed as one group per line
$groupNames = Get-Content file.txt
# The Foreach-Object section is only needed if $groupNames does not contain a valid -Identity value
# The Filter below uses Name attribute as an example because it assumes $groupNames contains Name attribute values. If it contains another attribute, update the filter accordingly.
$SamAccountNames = $groupNames | Foreach-Object {
Get-AdGroup -Filter "Name -eq '$_'" | Select-Object -Expand SamAccountName
}
# Storing the loop output into a variable is efficient provided you have enough memory for the operation.
# Alternatively, you can just pipe the `Get-AdGroupMember` into `Export-Csv -Append` but that could be a lot of writes!
$output = foreach ($group in $SamAccountNames) {
Get-AdGroupMember -Identity $group # You can use Select-Object here for specific properties
}
$output | Export-Csv -Path output.csv -NoTypeInformation

Pulling User Object's Primary SMTP from ProxyAddresses

I have a PS script that is pulling Employee IDs from a CSV file that I update every morning that I get from HR just to make sure the automation is running correctly by adding/changing their email, extensionAttribute 1, and the ProxyAddresses. I would like it to only check for the Primary SMTP instead of all ProxyAddresses but am having trouble.
Import-Csv "C:\temp\HRfeed101519.csv" | foreach {Get-ADUser $_.EmpID -Properties * | fL mail, extensionattribute1, Proxyaddresses}
The ProxyAddresses field identifies the PrimarySMTPAddress with the SMTP: tag. Therefore, you can query for that specifically and output it as a calculated property.
Get-ADUser $_.EmpID -prop ProxyAddresses,Mail,ExtensionAttribute1 |
Select-Object Mail,ExtensionAttribute1,ProxyAddresses,
#{Name='PrimarySMTPAddress';Expression={$_.ProxyAddresses -cmatch '^SMTP:' -creplace 'SMTP:'}}
-cmatch and -creplace perform case-sensitive regex matching.
Note: The default table display of the output may not show all of the properties and values due to collection size stored in ProxyAddresses. You can pipe your output to Format-List to see all properties, but do not store the Format-List output in a variable.

Adding AD User - P.O Box and Zip Code information Via Powershell

I have a list of users, Which serve as Shared Mailboxes - user objects,
In active directory.
The list is stored under TXT file ( usernames ).
in format:
user.name1user.name2
etc..
I Would like to add the following values for each user, listed in the file:
-PostalCode "01010101"
-POBox "000"
Previously , i have seen something like that suggested, with using
Set-ADUser command, something like:
Set-ADUser -Filter "UserPrincipalName -eq '$($_.userprincipalname)'" -PostalCode "01010101" -POBox "000"
This example is taken from another question , but, it has different parameters.
Please assist to create a complete script , which does the complete action.
Thanks everyone for your assistance.
If the TXT file contains usernames (SamAccountName), you can pipe the username values into a foreach loop and send them to Set-ADUser.
Get-Content Usernames.txt | Foreach-Object {
Set-ADUser -Identity $_ -PostalCode "01010101" -POBox "000"
}
The -Filter parameter can accept most AD attribute ldap display names for the given object class. The operator set is limited, but -eq is included. Using the pipeline into Foreach-Object, $_ will represent the current object in the pipeline, which will be one username from the TXT file. SamAccountName is used in the filter based on the assumption that usernames are SamAccountName values. If they are not, you can tweak the filter accordingly.

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

Referencing variables that are not strings

I want to reference properties selected from a cmdlet and then use them later on in my script as $mailboxarray.totalitemsize and $mailboxarray.totalitemsize
This is breaking later on in my script as I assume it doesn't like the type of object it is. How can I make anything I pull into the references a string? At the moment I am getting "No mapping exists from object type System.Management.Automation.PsObject to a known managed provider type". My code at the moment: the first command works fine but I can't use expandproperty when there are multiple entries like line two?
$recipienttype = Get-mailbox -identity $recordset.PrimarySmtpAddress | Select -expandproperty RecipientTypeDetails
$mailboxarray = Get-Mailbox -identity $recordset.PrimarySmtpAddress | Get-MailboxStatistics | Select-object totalitemsize, lastlogontime