Add-ADGroupMember Syntax - shell

I don't understand what I do wrong:
Get-ADPrincipalGroupMembership UserName | select name | where {$_.name -like "nac*"} | Add-ADGroupMember -Identity **$_.name** -Members UserName
This is the error I get:
Add-ADGroupMember : Cannot validate argument on parameter 'Identity'.
The argument is null. Provide a valid value for the argument, and then
try running the command again.
What should I put in the $_.name?

If you have a value stored in $Username be sure to include the $ character so PowerShell will recognize it as a variable. You also might want to remove the *s from the last cmdlet. This may not work as a one-liner. Try this:
$Group = Get-ADPrincipalGroupMembership $UserName | select name | where {$_.name -eq "nac*"}
Add-ADGroupMember -Identity $Group.Name -Members $UserName

Try this:
$groups = get-adprincipalgroupmembership $sourceuser | ? Name -like "nac*"
#check content of $groups
$groups | select Name
add-adprincipalgroupmembership $targetuser -memberof $groups
I'm sure this will work. Otherwise please post your error message.

You need to take care of the -Identity parameter the cmdlets can handle:
The Identity parameter should be one of:
A distinguished name (DN)
A GUID,
A security identifier (SID) or
A Security Accounts Manager (SAM) account name
Both cmdlets also allow an object to be sent through the pipeline to the Identity parameter.
For Add-ADGroupMember this would be a group object.
For Get-ADPrincipalGroupMembership you can use a user, group, or computer object.
This part of the code returns the group objects $UserName is a member of.
(remember: $UserName is the distinguished name, GUID, security identifier, or SAM account name of the user.)
Get-ADPrincipalGroupMembership $UserName | Where-Object { $_.Name -like "nac*" }
Next you want to add a different user to the groups $UserName is a member of, right?
In that case, set up a variable to store the second user in, again use the distinguished name,
GUID, security identifier, or SAM account name and then use something like this:
Get-ADPrincipalGroupMembership $UserName | Where-Object { $_.Name -like "nac*" } | Add-ADGroupMember -Members $AnotherUserToAddToThisGroup

Related

In Powershell how can I remove the first x number of characters from Get-ADUser results?

I have a list of results from Get-ADUser giving me all users in an OU. The format of the output username is '-prefix-username'. I need to remove the 7 character '-prefix-' and then conduct another Get-ADUser lookup against the remaining 'username' portions. The issue I'm finding is that if I run just the second Get-ADUser lookup where I set $User as just one specific '-prefix-username' it works fine but when I try to process a list I either get an error where there seems to be space after the trimmed username (txt format list - Get-ADUser : Cannot find an object with identity: 'user ' under:) or the username includes a " that I can't remove from the end of the username (csv format list - Get-ADUser : Cannot find an object with identity: 'user"').
So far I have:
get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 |
Select SAMAccountName |
Out-File C:\Temp\UserList.txt
$UserList = (Get-Content C:\Temp\UserList.txt)
$StandardUsers = ForEach($User in $UserList) {
Write-Host "Now checking $User"
Get-ADUser $User.Substring(7) -Properties * |
Select-object DisplayName, UserPrincipalName, Mail, Manager,EmployeeID
}
$StandardUsers | Out-File -FilePath C:\Temp\StandardUserList.txt
First thing to mention is that if you create the list using Select -ExpandProperty SAMAccountName, you would only get SamAccountnames in the file.
Having said that, why bother with an 'in-between' file at all and simply do:
# By default, Get-ADUser returns these properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
# Only ask for properties that are not already in this list.
Get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 -Properties DisplayName, EmailAddress, Manager, EmployeeId |
Select-Object DisplayName, UserPrincipalName, EmailAddress, Manager,EmployeeID |
Set-Content -Path 'C:\Temp\StandardUserList.txt'
You are likely having issues with saving it to a file (where it gets formatted) and then reading it back in. The formatting could be adding " and reading a newline (which you think is a space) character. If you really need to save it then do the following (else just hook up the pipelines):
$userList = Get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 |
Select-Object SAMAccountName
$userList |
Out-File C:\Temp\UserList.txt
$standardUsers = $userList |
Select-Object -ExpandProperty SAMAccountName -PipelineVariable user |
ForEach-Object {
Write-Host "Now checking $user"
$userWithoutPrefix = ($user -Replace '^-prefix-','') -Replace '(\w|\n)$','' # to use a more advanced version of the suggestion by #Avshalom
Get-ADUser $userWithoutPrefix -Properties * | Write-Output
} |
Select-Object DisplayName, UserPrincipalName, Mail, Manager, EmployeeID
$standardUsers | Out-File -FilePath C:\Temp\StandardUserList.txt

How do I remove all the groups from disabled Active Directory Users via Powershell?

I'm trying to gather all the disabled users in our Active Directory and trying to remove the disabled users from all their groups. Mostly for cleanup purposes. I'm a bit stuck on my script. I'm not sure what to put after Remove-ADPrincipalGroupMembership:
$disabled_users = Get-AdUser -SearchBase "Ou=Users, Ou=test, DC=testdomain, DC=io" -Filter
"enabled -eq 'false'"
foreach($person in $disabled_users) {
Get-ADPrincipalGroupMembership $person | Remove-ADPrincipalGroupMembership #stuckhere
}
Get-ADPrincipalGroupMembership returns only groups, leading Remove-ADPrincipalGroupMembership to auto-fill -Identity with the group name. You'll have to re-use the user object in -Identity.
Because of the first issue, Remove-ADPrincipalGroupMembership doesn't accept multiple groups from the pipeline. It should normally, but the [ADGroup] objects returned by Get-ADPrincipalGroupMembership seem to trip it up. To fix, use a ForEach loop, or use a two-step process:
# two steps:
$groups = Get-ADPrincipalGroupMembership $person
Remove-ADPrincipalGroupMembership -Identity $person -MemberOf $groups -WhatIf
# OR foreach loop:
Get-ADPrincipalGroupMembership $person |
Foreach {
Remove-ADPrincipalGroupMembership -Identity $person -MemberOf $_
}
Note that you can't remove an AD user's primary group (usually 'Domain Users'), so you may want to add a filter:
$groups = Get-ADPrincipalGroupMembership $person |
Where Name -notlike 'Domain Users'
Remove-ADPrincipalGroupMembership -Identity $person -MemberOf $groups
Adding another option using Remove-ADGroupMember instead:
Get-ADPrincipalGroupMembership $person | Remove-ADGroupMember -Members $person
Remove-ADGroupMember will take the distinguishedNames of the user's membership as pipeline value so you only need to specify the Member of the group you want to remove.

Copy Groups from one user to another in AD, except one specific group

Need help with adding a small comand to finish this pwoershell command.
I have this powershell command that copy groups from one user to another.
Now what i need is to add a command that will "Except" a specific group, like it will copy all the groups except one specific group.
Thanks for help.
Get-ADUser -Identity $Oldusername -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $Newusername
Get-ADUser -Identity $Oldusername -Properties memberof | Select-Object -ExpandProperty memberof | Where-Object { $_ -NotMatch $grouptoexclude } | Add-ADGroupMember -Members $Newusername
$grouptoexclude containing the name of the group you don't want the new user to be added into. It must be a distinguished name like CN=GroupName,OU=Groups,OU=Users & Workstations,DC=Fabrikam,DC=COM

Powershell script not reading AD phone numbers

I am trying to edit the formatting of a group of user's phone numbers in AD. Specifically, replacing '-' characters with ' '. However, I do not seem to be able to access the existing phone number, which I need to do to replace the characters. I understand the -OfficePhone flag under Set-ADUser sets the telephoneNumber attribute, which seems to be working and the telephoneNumber attribute is there with the expected value in Attribute Editor as well. However when I try to access $user.telephoneNumber it comes up blank.
Here is my code, commented with what works/what doesn't and some behaviors:
foreach ($user in $users) {
# Works. Prints out various basic attributes of user
Write-Output $user
# Doesn't work. Prints blank
Write-Output $user.telephoneNumber
# Works
Set-ADUser -Identity $user -OfficePhone '555555555'
}
As AdminOfThings has stated, you need to make the property accessible. You do this by using the -Properties parameter on the Get-ADUser command. Here is an example:
Get-ADUser -Identity USER_NAME -Properties TelephoneNumber
If you wanted to get all the properties back, you can use:
Get-ADUser -Identity USER_NAME -Properties *

Account expiry dates or account Never expire for all AD users

While I am running the below command getting expiration_date is blank.
Is it possible to get the 'Never expire' instead of blank in expiration_date?
Import-Module ActiveDirectory
$Groups = Get-ADGroup -filter {Name -like "SSL_VPN_Users" } | Select-Object Name
ForEach ($Group in $Groups) {
Get-ADGroupMember -identity $($group.name) -recursive |
Get-ADUser -Properties samaccountname,mail,AccountExpires |
select samaccountname,mail,#{l="expiration_date";e={[datetime]::fromfiletime($_.accountexpires)}} |
Export-csv -path C:\SSLVPN\SSL_VPN_Users.csv -NoTypeInformation
}
The problem is probably when the account never expires the value of AccountExpires is the max. int64 value which results in an ArgumentOutOfRangeException when calling [datetime]::FromFileTime for it.
Therefore try the following - I introduced the helper function accountExpiresToString for better readability of the expression script block but you can pack the function's code directly within the script block if you prefer that.
function accountExpiresToString($accountExpires) {
if (($_.AccountExpires -eq 0) -or
($_.AccountExpires -eq [int64]::MaxValue)) {
"Never expires"
}
else {
[datetime]::fromfiletime($accountExpires)
}
}
Import-Module ActiveDirectory
...
ForEach ($Group in $Groups) {
Get-ADGroupMember ... |
Get-ADUser -Properties ...,AccountExpires |
Select-Object #{l="expiration_date";e={ accountExpiresToString($_.AccountExpires)}} |
Export-Csv ...
}
Update: If of interest, here is a page on MSDN describing that 0 and 0x7FFFFFFFFFFFFFFF ([int64]::MaxValue) indicates an account that never expires.

Resources