I have 2 server in my company one is Us.local(<--main domain) and 2nd is India.local
we get the bulk termination in our india.local domain and I want to remove all AD groups from the tab. I am using the below mentioned script to remove all members of groups.
Note: There is no issue with users account we can disable and remove groups manually
$users= import-CSv -Path C:\Users\Desktop\DisableUsers.csv
$totalcount = $users.Count
write-host $totalcount
$currentCount = 1
Foreach ($u in $users)
{
#Remove members from DL (AD)
Get-ADUser -Server:"addc45.india.local" $u.UserID -Properties MemberOf | Select -Expand MemberOf | %{Remove-ADGroupMember $_ -member $u.UserID -Confirm:$false }
Write-host "Disabled" $u.UserID $currentCount "/" $totalcount
$currentCount++
}
I am getting the below mentioned error every time I use powershell.
Remove-ADGroupMember : A referral was returned from the server
At line:15 char:125
+ ... emberOf | %{Remove-ADGroupMember $_ -member $u.UserID -Confirm:$false ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (CN=VDI-IN-EQ-SV...health,DC=local:ADGroup) [Remove-ADGroupMember], ADReferralException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8235,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember
Remove-ADGroupMember : Cannot find an object with identity: 'IN100040' under: 'DC=US,DC=local'.
At line:15 char:125
+ ... emberOf | %{Remove-ADGroupMember $_ -member $u.UserID -Confirm:$false ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (IN100040:ADPrincipal) [Remove-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember
I am receiving error message when running the following script, any idea why?
PS C:\Users\npevltdisdddtda_1> $userList = Import-Csv C:\temp\Text.csv
foreach ($user in $userList) {
# Get-ADUser -Filter "SamAccountName -eq '$($user.SamAccountName)'" | {Set-ADUser -SmartCardLogonRequired:$true}
Get-ADUser -filter "SamAccountName -eq '$($user.SamAccountName)'" | {Set-ADUser -SmartcardLogonRequired:$true}
}
At line:5 char:77
+ ... ($user.SamAccountName)'" | {Set-ADUser -SmartcardLogonRequired:$true}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expressions are only allowed as the first element of a pipeline.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline
I inherited several PowerShell scripts, to place a user on LitigationHold in Exchange, as well as set the user's AD protect from accidental deletion to $true.
They all work separately, but one uses User Full name, and the other uses the SAM account name. I am trying to marry scripts so that I can just use the Full name, but I can't seem to pass the SAMAccountName .
My attempt at combining the codes:
foreach ($user in ("Name 1", "Name 2", "Name 3"))
{
$mailuser = Get-Mailbox $user -DomainController A1.Domain l -ErrorAction SilentlyContinue| Select *;
if ($mailuser -eq $null)
{
Write-Host "$user was not found. Check for misspellings."
}
else
{
if($mailuser.LitigationHoldDate -ne $null)
{
Set-Mailbox $user -LitigationHoldEnabled:$true -Confirm:$False -Force:$True -DomainController A1.Domain;
Write-Host "$user is now placed on hold.";
$userinfo = {
Get-ADUser $user -Server A1.Domain
};
Set-ADObject -Identity $userinfo.SamAccountName -ProtectedFromAccidentalDeletion:$true;
$i = Get-ADUser $user -Properties description -Server A1.Domain |
%{ $_.description } |
Set-ADUser $userinfo -Server A1.Domain -Replace #{
description="8/19/2019 - Security Hold, please contact admin before modifying `r`n | $($i)"
}
}
else{
Write-Host "$user is already on litigation hold as of $($mailuser.LitigationHoldDate) by $($mailuser.LitigationHoldOwner)."
}
}
}
To take list of Display names and get usernames:
foreach ($user in ("Name 1", "Name 2", "Name 3"))
{
$userinfo = Get-ADUser -filter { DisplayName -like $user } -Server A1.Domain ;
if ($userinfo -ne $null)
{
Get-ADUser -filter { DisplayName -like $user } -Server A1.Domain | ft SamAccountName -HideTableHeaders
}
else
{
Write-Host "$user is not available"
}
}
To Add Lit Hold into AD Description
foreach ($user in ("Name 1", "Name 2", "Name 3"))
{
$mailuser = Get-Mailbox $user -DomainController A1.Domain -ErrorAction SilentlyContinue| Select *;
if($mailuser -eq $null)
{
Write-Host "$user was not found. Check for misspellings."
}
else
{
if ($mailuser.LitigationHoldDate -eq $null)
{
$i = Get-ADUser $user -Properties description -Server A1.Domain | %{ $_.description};
Set-ADUser $user -Server A1.Domain -Replace #{
description="Security Hold, please contact the Gnome before modifying `r`n | $($i)"
}
}
else
{
Write-Host "$user is already on litigation hold as of $($mailuser.LitigationHoldDate) by $($mailuser.LitigationHoldOwner)."
}
}
}
To take a list of Display names and set Lit Hold:
foreach ($user in ("Name 1", "Name 2", "Name 3""))
{
$mailuser = Get-Mailbox $user -DomainController A1.Domain -ErrorAction SilentlyContinue| Select *;
if ($mailuser -eq $null)
{
Write-Host "$user was not found. Check for misspellings."
}
else
{
if($mailuser.LitigationHoldDate -eq $null)
{
Set-Mailbox $user -LitigationHoldEnabled:$true -Confirm:$False -Force:$True -DomainController A1.Domain ;
Write-Host "$user is now placed on hold."
}
else
{
Write-Host "$user is already on litigation hold as of $($mailuser.LitigationHoldDate) by $($mailuser.LitigationHoldOwner)."
}
}
}
To take a list of usernames and protect against accidental deletion:
"User1", "User2", "User3" | Get-aduser -Server A1.Domain | Set-ADObject -ProtectedFromAccidentalDeletion:$true
I want to account to be set to LitigationHold, AD protect from accidental deletion, also reflect security hold on description.
This is the error message I get when I run it:
FN LN is now placed on hold.
Set-ADObject : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the
command again.
At line:9 char:25
+ Set-ADObject -Identity $userinfo.SamAccountName -ProtectedFromAccide ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-ADObject], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.SetADObject
Set-ADUser : A positional parameter cannot be found that accepts argument 'Get-ADUser $user -Server A1.domain '.
At line:12 char:1
+ Set-ADUser $userinfo -Server A1.domain -Replace # ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser
I was trying to see if I can bypass the -Identify flag by giving it the user full name, but Set-ADObject will only take an object, not a string.
--edit 3--
Replying to #Seth about -Identity flag is a parameter:
changed part of the code to give -Identity an ADObject:
$userinfo = Get-ADUser {DisplayName -like $user} -Server A1.domain};
Set-ADObject $userinfo -ProtectedFromAccidentalDeletion:$true;
The error message is as follows:
Get-ADUser : Cannot evaluate parameter 'Identity' because its argument is specified as a script block and there is no input. A script block cannot be
evaluated without input.
At line:8 char:26
+ $userinfo = Get-ADUser {DisplayName -like $user} -Server A1.domain ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Set-ADObject : Cannot evaluate parameter 'Identity' because its argument is specified as a script block and there is no input. A script block cannot be
evaluated without input.
At line:9 char:15
+ Set-ADObject $userinfo -ProtectedFromAccidentalDeletion:$true;
+ ~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [Set-ADObject], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.ActiveDirectory.Management.Commands.SetADObject
Set-ADUser : A positional parameter cannot be found that accepts argument 'Get-ADUser {DisplayName -like $user} -Server A1.domain'.
At line:12 char:1
+ Set-ADUser $userinfo -Server A1.domain -Replace # ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser
I think at this point the issue boils down to: Set-ADUser uses SamAccountName, and I can't seem to parse out the SamAccountName from the user ADObject. I can get the SamAccountName by calling a table from the ADObject, but it will not pass into Set-ADUser correctly.
You're currently not doing any verification on whenever you actually get a proper ADUser object. You simply assume that the assignment to $i/$userinfo will be successful. Your $name contains the display name for a user. So for example it would be "John Doe".
This works for Get-Mailbox because it supports Name, Alias, Distinguished name (DN), Canonical DN, <domain name>\<account name>, Email address, GUID, LegacyExchangeDN, SamAccountName, User ID or user principal name (UPN) as values for Identity. It has to do this to an extend because some values might or might not be available to identify a mailbox. Get-ADUser on the other hand has a much more strict approach only supporting distinguished name, GUID (objectGUID), security identifier (objectSid), SAM account name (sAMAccountName). Hence using the display name to find an AD account isn't supported. Your colleague used a filter to just use it anyway which is one solution $userinfo = Get-ADUser -filter { DisplayName -like $user } -Server A1.Domain ;.
If you really want to go with the display name you'll need to either look for it like that or use the DistinguishedName property of the mailbox to get the owner. So you'd do something like:
$mailbox = Get-Mailbox test
$adObject = Get-AdUser -Identity $mailbox.DistinguishedName
Obviously you should check whenever the property actually exists on the mailbox object as it might be disconnected. Also rather than using $user again and again you might want to use actual object (e.g. the mailbox or AD Object) to make sure you only need to verify your search results once.
You should also be able to just use one Set-AdUser call instead of that very weird call you're currently doing. You find the user, iterate the descriptions for the user (an object only has one) and add to it. Doing something like Set-AdUser $adObject -Description "New Description | $($adObject.Description)" would be much shorter and clearer. Spreading it some more might even improve it more.
I move automatically all ad disabled accounts in OU adding the date of deactivation in extensionattribute4 with this the script :
import-module activedirectory
$timer = (Get-Date)
$TargetOU = "OU=Disabled Accounts,DC=domain,DC=lan"
$DisabledAccounts = get-aduser -filter { enabled -eq $false } -SearchBase "OU=Test,OU=EMEA,DC=domain,DC=lan"
ForEach ($account in $DisabledAccounts) {
set-aduser -Identity $account.distinguishedName -add #{extensionAttribute4="$timer"}
}
ForEach ($account in $DisabledAccounts) {
Move-ADObject -Identity $account.distinguishedName -TargetPath $TargetOU
But when I want to remove the ad disabled accounts with the reference the date of extensionattribute4 less 90 days with the script :
import-module activedirectory
$DaysInactive = 90
$time = (Get-Date).Adddays(-($DaysInactive))
$DisabledAccounts = get-aduser -filter { extensionattribute4 -lt $time -and enabled -eq $false } -SearchBase "OU=Disabled Accounts,DC=domain,DC=lan"
ForEach ($account in $DisabledAccounts) {
Remove-ADObject -Identity $account.distinguishedName
}
I have got an error :
get-aduser : Invalid type 'System.DateTime'.
Parameter name: extensionattribute4
At C:\removedisabledadaccounts.ps1:4 char:21
+ $DisabledAccounts = get-aduser -filter { extensionattribute4 -lt $time -and enab ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : Invalid type 'System.DateTime'.
Parameter name: extensionattribute4,Microsoft.ActiveDirectory.Management.Commands.GetADUser
The error indicates you are trying to do an operation that the attribute does not accept. When you populated the field in your earlier operation you converted the date to a string with #{extensionAttribute4="$timer"}. I can't imagine those attributes are stored as anything other than strings anyway. In fact trying to store the date object ends in similar failure.
Kudos for using -Filter but I am sure this is something beyond the -Filter/-LDAPFilter so you should just have to do some post processing.
Get-ADUser -Filter {enabled -eq $false} -SearchBase "OU=Disabled Accounts,DC=domain,DC=lan" -Properties extensionattribute4 |
Where-Object{$time -ge $_.extensionattribute4}
Since we need to work with that attribute we need to be sure it is returned in the -Properties list.
I am trying to get a list of users where the telephone attrib is null and update the atrrib with a phone number, so far here is what I have:
$allen=gc "C:\0NIX\03SCRIPTS\TMP\jkirb\allen.txt"
$phonenumber = "972-xxx-xxx"
FOREACH ($user in $allen)
{
$nophone = get-aduser $user -pr *| where {$_.telephonenumber -eq $null} | select samaccountname |ft -HideTableHeaders
Set-ADuser -identity "$nophone" -replace #{telephonenumber="$phonenumber"}
}
Which is erroring with this:
Set-ADuser : Cannot find an object with identity: 'Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData
Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData' under:
'DC=bhcs,DC=pvt'.
At line:7 char:1
+ Set-ADuser -identity "$nophone" -replace #{telephonenumber="$phonenumber"}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Microsoft.Power...t.FormatEndData:ADUser) [Set-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : Cannot find an object with identity: 'Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Mic
rosoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData' under: 'DC=
bhcs,DC=pvt'.,Microsoft.ActiveDirectory.Management.Commands.SetADUser
You are adding some custom formatting to your object when you use any of the Format-* cmdlets (Format-Table in your case) and this ruins the object for future pipeline use.
Try this instead:
$allen=gc "C:\0NIX\03SCRIPTS\TMP\jkirb\allen.txt"
$phonenumber = "972-xxx-xxx"
FOREACH ($user in $allen)
{
$nophone = get-aduser $user -pr *| where {$_.telephonenumber -eq $null}
Set-ADuser -identity "$nophone" -replace #{telephonenumber="$phonenumber"}
}