Powershell - Adding users to AD group from a CSV file - powershell

I know this has been done to death but im useing this as a learning experience with powershell. Could someone take a look at my code and tell me where i am going wrong? Noob code warning!
#
# Add User to an AD Group
#
#
# get arguements and quit if they dont exist
$CSV = $args[0]
$GROUP = $args[1]
if (! $CSV) {
Write-Host "Please format this command as 'AddUsersToGroup <csv file> <AD group>'"
Write-Host "CSV file must have the header 'UserName' with AD usernames following"
exit
}
# Read csv file for users and add to AD group
Import-module ActiveDirectory
Import-CSV "$CSV" | % {
# Get existing users from AD group
$ExistingGroup = "Get-ADGroupMember $GROUP | Select-Object SamAccountName"
# create new array removing existing users from the csv
$NewGroup = $ExistingGroup | where {$CSV -notcontains $_}
# add the users to the AD Group from the new array
Add-ADGroupMember -Identity $NewGroup -Member $_.UserName
exit
}

try delete double quote here:
$ExistingGroup = Get-ADGroupMember $GROUP | Select-Object SamAccountName
with quote you're assign a string value to variable not the results of your commands

Related

[PowerShell]Get-Content and Add Column Entry?

I am trying to input a list of users into PowerShell and get a specific security group attached to the user's account. At this current time, I have two pieces - an Excel sheet with multiple pieces of data, and a .txt with just the user's usernames. The script I have currently just inputs the user's usernames from the .txt and gets the security group from their account that matches a specific prefix, however I noticed doing it this way doesn't give any specific order. Even though the users are in a specific order (copied and pasted exactly from the excel document), the actual output doesn't come back well.
So, here's what I'd Like to do now, I just don't know how. I would like to get the content from the Excel document, take all of the usernames and do Get-ADPrincipalGroupMembership like I am now, and then write the security group Back to the line that matches the username. For example, if I looked up the SG for msnow, it would get the SG for msnow and then write the SG back to the row that has msnow, and continues through the list. Instead of just doing an Out-GridView, it would actually write this to the Excel document.
Any help on making this work?
Here is the code I have right now.
Import-Module ActiveDirectory
$Names = Get-Content C:\Temp\Users.txt
$Records = #()
Foreach ($ADUsers in $Names) {
Try {
$SG = Get-ADPrincipalGroupMembership -Identity $ADUsers | Select Name | Where {$_.Name -Like "SG - *"}
$SGName = $SG.Name
}
Catch [ADIdentityNotFoundException] {
$SGName = "User not found"
}
$Records += New-Object PSObject -Property #{"UserName" = $ADUsers;"Security Group" = $SGName}
}
Write-Host "Generating CSV File..."
$Records | Out-GridView
Thank you!
If you save the Excel as CSV, so it will look something like
"UserName","Security Group","InsideInfo"
"bloggsj","","tall guy"
"ftastic","","nothing worth mentioning"
things shouldn't be that hard to do.
$out = 'D:\Test\Updated_usersandgroups.csv'
$csv = Import-Csv -Path 'D:\Test\usersandgroups.csv'
Write-Host "Updating CSV File..."
foreach ($user in $csv) {
try {
$SG = Get-ADPrincipalGroupMembership -Identity $user.UserName -ErrorAction Stop
# if more groups are returned, combine them into a delimited string
# I'm using ', ' here, but you can change that to something else of course
$SGName = ($SG | Where-Object {$_.Name -Like "SG - *"}).Name -join ', '
}
catch [ADIdentityNotFoundException] {
$SGName = "User $($user.UserName) not found"
}
catch {
# something else went wrong?
$SGName = $_.Exception.Message
}
# update the 'Security Group' value
$user.'Security Group' = $SGName
}
Write-Host "Generating updated CSV File..."
$csv | Export-Csv -Path $out -UseCulture -NoTypeInformation
# show output on screen
$csv | Format-Table -AutoSize # or -Wrap if there is a lot of data
# show as GridView (sorts by column)
$csv | Out-GridView
Output in console would then look like
UserName Security Group InsideInfo
-------- -------------- ----------
bloggsj SG - Group1, SG - Group1 tall guy
ftastic SG - Group1 nothing worth mentioning
Note: I don't know what delimiter your Excel uses when saving to CSV file. On my Dutch machine, it uses the semi-colon ;, so if in your case this is not a comma, add the delimiter character as parameter to the Import-Csv cmdlet: -Delimiter ';'
Excel uses whatever is set in your locale as ListSeparator for the delimiter character. In PowerShell you can see what that is by doing (Get-Culture).TextInfo.ListSeparator. On output, the -UseCulture switch will make sure it uses that delimiter so Excel will understand

move AD group by file

I'm new with PS and doing my first steps..
I have a file named "C:\temp\used_groups.csv".
The file has email address of AD Groups populated by Powershell script to check which distributions group are being used in 365.
Now I want to be able to move them to different OU.
the file has some AD group's email address as follow:
"RecipientAddress"
"test#test.com"
"test1#test.com"
"test2#test.com"
is it possible to move the AD group only by their email address attribute?
how can I resolve the group's sAMAccountName attribute by their email address attribute?
this is what I tried with no success:
$Groups=import-csv "C:\temp\used_groups.csv"
ForEach ($Group in $Groups){
Get-ADGroup -Filter "mail -like $Group "
# rest of script.. not done yet.
}
I would do something like this:
# put the DistinghuishedName of the destination OU here
$destinationOU = "OU=Test,DC=Fabrikam,DC=COM"
# read the CSV and grab the 'RecipientAddress' fields in an array
$emailAddresses = (Import-Csv "C:\temp\used_groups.csv").RecipientAddress
foreach ($email in $emailAddresses){
$GroupToMove = Get-ADGroup -Filter "mail -like '$email'"
if ($GroupToMove) {
# Move-ADObject takes the 'DistinghuishedName' or the 'objectGUID' as Identity parameter
# but it also works when piping the group object itself to it.
$GroupToMove | Move-ADObject -TargetPath $destinationOU
Write-Host "Moved group '$($GroupToMove.Name)'."
}
else {
Write-Warning "Could not find group with email address '$email'"
}
}
When using a CSV you have to specify the fieldname. Another problem in your script is the absence of quotes in the AD filter.
Try this:
$Groups=import-csv "C:\temp\used_groups.csv"
ForEach ($Group in $Groups){
(Get-ADGroup -Filter "mail -like '$($Group.RecipientAddress)'").samaccountname
# rest of script.. not done yet.
}
Cheers,
Gert Jan

How do you export a list of PC names and a specific group membership of that endpoint using powershell?

I have a list of end points and we are trying to see if they have this specific group membership but I cannot figure out how to export the endpoint and the group its a member of.
$Groups = foreach ($pc in (Get-Content "C:\Users\*\Desktop\DefualtTest.csv")) {
try {
Get-ADComputer $pc -Properties memberof |
select -Expand memberof |
dsget group -samid |
? {$_ -match 'bit9'}
} catch {
Write-Output "$pc does not have bit9 group"
}
}
$Groups | Out-File "C:\Users\*\Desktop\testONE.csv"
trying to do this in comments is ... to difficult. [grin]
here's an example of what i mean by "do it one line at a time" in the foreach loop ...
# fake reading a list of systems from a text file
# in real life, use Get-Content
$ComputerList = #'
pc01
pc02
pc03
pc04
pc05
pc666
'# -split [environment]::NewLine
# fake getting a list of Computers & the groups they are in
# in real life, use Get-ADComputer & the ".MemberOf" property
$GroupMembershipLookup = #{
'pc01' = #('GroupA', 'GroupB')
'pc02' = #('GroupB', 'GroupC', 'GroupD')
'pc03' = #('GroupA', 'GroupB', 'GroupE')
'pc04' = #('GroupZ')
}
$NoGroupFound = '__No Group Found__'
$Results = foreach ($CL_Item in $ComputerList)
{
# use a real call to Get-ADComputer here [*grin*]
# pro'ly something like "(Get-ADComputer $CL_Item -Property MemberOf).MemberOf -join '; '"
$GroupList = $GroupMembershipLookup[$CL_Item] -join '; '
if ([string]::IsNullOrEmpty($GroupList))
{
$GroupList = $NoGroupFound
}
[PSCustomObject]#{
ComputerName = $CL_Item
GroupMembership = $GroupList
}
}
# on screen
$Results
# to CSV
$Results |
Export-Csv -LiteralPath "$env:TEMP\Del_GroupMembershipList.csv" -NoTypeInformation
on screen output ...
ComputerName GroupMembership
------------ ---------------
pc01 GroupA; GroupB
pc02 GroupB; GroupC; GroupD
pc03 GroupA; GroupB; GroupE
pc04 GroupZ
pc05 __No Group Found__
pc666 __No Group Found__
csv content ...
"ComputerName","GroupMembership"
"pc01","GroupA; GroupB"
"pc02","GroupB; GroupC; GroupD"
"pc03","GroupA; GroupB; GroupE"
"pc04","GroupZ"
"pc05","__No Group Found__"
"pc666","__No Group Found__"
what the above does ...
creates an array of system names as if they had been read in via Get-Content
creates a lookup table as if one had used Get-ADComputer to get the group membership for each system
made a "not found" value & stored that in a $Var for reuse
iterated thru the $ComputerList collection
grabbed the list/array of groups and converted them into a semicolon delimited string
tested for "no groups found" & added the value saved earlier if the list was empty
built a [PSCustoObject] and sent that to the output stream
captured the output stream to an array named $Results all at one time to avoid the += array penalty
displayed the results on screen
sent the $Results collection to a CSV file

Powershell command to update employee number from csv

I am trying to write a powershell script that will update employeeID attribute in AD for each user
The script needs to update employeeID from my CSV file
Sample CSV:
user,employeeID
user1,1234567
At least now you are trying some code which looks like it should work. Your logic is sound. Are you sure your CSV does not contain and blanks? Some simple statements could rule those out.
Import-CSV "C:\Scripts\Users.csv" | ForEach-Object {
$User = $_.UserName
$ID = $_.EmployeeID
If($user -and $ID){
Set-ADUser $User -employeeID $ID
} Else {
Write-Warning "User or employee number is null. Check source."
}
The If statement would fail if either $user or $id was null. If that is not the case and your CSV does contain data maybe you are having an encoding issue.
I think it depends on how you're finding the user in Active Directory... You could try something like this:
# import the users
$myUsers = Import-Csv csvFile.csv
# loop through each user and update their employeeID property
foreach ($user in $myUsers)
{
# the Set-ADUser cmdlet requires a type of System.Hashtable<>,
# so let's create one
$updateRecord = #{"EmployeeID"=$user.EmployeeID}
# Set the user attribute
Set-ADUser -Identity $user -Replace #updateRecord
}
This might do the trick. Did you guys modify the AD Schema? Keep in mind that "EmployeeID" is assuming you have an EmployeeID Attribute on your Active Directory users.
Please let me know if it helps!

Determining if a given user is in a given global group

I’m trying to search through Active Directory using the AD module in PowerShell. I’m trying to determine whether a given user is in a given global group. The issue is that I’m using -match meaning if there is a username that contains another within it, such as 'smith_pl' containing 'smith_p'. The user 'smith_p' will be shown to be in the group.
So my question is: Is there a better way of getting a $True or $False return depending if a user is in a giving global group using the AD module?
If not
Is there a way of getting the output from $ListOfmembers into an array so I can use -eq instead of -match?
Part of Script:
$ListOfmembers = dsquery group domainroot -name $globalgroup |
dsget group -members |
dsget user -samid -L
$checkMember = $False
#Search if the user is in output the list
If($ListOfmembers -match $Logonname){
$checkMember = $True
}
ListOfmembers Output:
samid: user05_t
samid: user23_s
samid: Admin
samid: user45_s
dsget succeeded
Any help would be appreciated, Cheers.
$member = Get-ADGroupMember group1 -Recursive | where {$_.samaccountname -eq 'user1'}
if($member) {'user 1 is a member of group1'}
You can do it like this:
[reflection.assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement")
$username = "samaccountname"
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username)
$g = $user.GetGroups()
( $g | select -expa name ) -contains 'groupname'
You should checkout QAD: http://www.quest.com/powershell/activeroles-server.aspx
$user get-qaduser samAccountName
$user.memberof