PowerShell to Remove ADGroup from Active Directory - powershell

start-transcript -path c:\docs\MyTranscript.txt
$WhenChangedDate = ((get-date).addmonths(-12)) #has not been modified in over a year
$domain = "Domain1"
$emptygroups = Get-ADGroup -Filter * -Properties members, whenchanged -server $domain| Where-Object {($_.members.count -eq 0) -and ($_.whenchanged -le $WhenChangedDate)} | Select-Object -last 10
#$emptygroups = Get-ADGroup -Filter * -Properties members, whenchanged -server $domain | Where-Object { ($_.members.count -eq 0) -and ($_.whenchanged -le $WhenChangedDate) -and ($_.name -notlike '*CTX*')} | Select-Object -last 10
$emptygroups.name | %{REmove-adgroup $_ -Confirm:$false -WhatIf}
Stop-transcript
I'm getting the below error for Domain1. However, it runs successfully on Domain2. Any ideas?
Remove-ADGroup : 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:1 char:38
+ $emptygroups.name | %{REmove-adgroup $_ -Confirm:$false -WhatIf}
+ ~~
+ CategoryInfo : InvalidData: (:) [Remove-ADGroup], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.
Commands.RemoveADGroup

What you're trying to do can be accomplished using the following LDAPFilter:
"(&(!member=*)(whenChanged<=$date)(!name=*CTX*))"
& All conditions must be met.
!member=* Group without members.
whenChanged<=$date WhenChanged lower than a specified date.
!name=*CTX* Name not like CTX.
$domain = "Domain1"
$date = [datetime]::Today.AddYears(-1).ToString('yyyyMMddHHmmss.sZ')
Get-ADGroup -LDAPFilter "(&(!member=*)(whenChanged<=$date)(!name=*CTX*))" -Server $domain |
Select-Object -Last 10 |
Remove-ADGroup -Confirm:$false -WhatIf

Related

Update Active Directory (On-Prem) User Attribute via Powershell

I tried to not bug you all, but I'm at a loss. I'll preface with, I'm still relatively new to PS, so my apologies for any ignorance.
Need: To update users' attribute (extensionAttribute1 to be precise) to "First.Last" (or rather, "givenName.Surname") for all users in AD.
Problem: When I try to run the Powershell below (I was trying 2 different methods for update, hence the commented out portion), I get the outputs below.
Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase 'ou=Users,ou=Test,dc=Sample,dc=Com' |
Select SamAccountName |
Export-Csv -Path 'c:\Scripts\AllUsersSamaccountname.CSV' -NoTypeInformation
$file="c:\Scripts\AllUsersSamaccountname.CSV"
(gc $file | select -Skip 1) | sc $file
$Users = Import-Csv -Path "c:\Scripts\AllUsersSamaccountname.CSV" -Header "AccountName"
foreach($User in $Users){
$ADUser = Get-ADUser -Identity $User.AccountName -Properties extensionAttribute1
$ADUserG = Get-ADUser -Identity $User.AccountName -Properties givenName
$ADUserS = Get-ADUser -Identity $User.AccountName -Properties Surname
#$ADUser.extensionAttribute1 = [Array]$ADUserG + '.' + $ADUserS
Set-ADUser -Instance $ADUser -replace #{extensionAttribute1=([Array]$ADUserG + '.' + $ADUserS)}
}
Get-ADUser -Filter * -SearchBase 'ou=Users,ou=Test,dc=George,dc=Com' |
Select extensionAttribute1 |
Export-Csv -Path 'c:\Scripts\new-AllUserinfo6.CSV' -NoTypeInformation
Output for Set-ADUser -Instance $ADUser -replace #{extensionAttribute1=([Array]$ADUserG + '.' + $ADUserS)
Set-ADUser : Cannot validate argument on parameter 'Replace'. All values in the argument collection should be of
the same type.
At line:17 char:44
+ ... er -replace #{extensionAttribute1=([Array]$ADUserG + '.' + $ADUserS)} ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.Set
ADUser
Output for #$ADUser.extensionAttribute1 = [Array]$ADUserG + '.' + $ADUserS
Exception setting "extensionAttribute1": "The adapter cannot set the value of property "extensionAttribute1"."
At line:16 char:6
+ $ADUser.extensionAttribute1 = [Array]$ADUserG + '.' + $ADUserS
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterSetValue
Any help or guidance would be greatly appreciated...
You are casting the givenName to an array. More than likely that's causing the whole expression to return an array, which isn't acceptable for extensionAttribute1.
I didn't test this but rewriting the loop to something like below should work:
foreach($User in $Users)
{
$ADUser = Get-ADUser -Identity $User.AccountName -Properties extensionAttribute1
$ADUserG = Get-ADUser -Identity $User.AccountName -Properties givenName
$ADUserS = Get-ADUser -Identity $User.AccountName -Properties Surname
$extensionAttribute1 = ($ADUserG.givenName + '.' + $ADUserS.Surname)
$ADUser.extensionAttribute1 = $extensionAttribute1
Set-ADUser -Instance $ADUser
}
Note: that you must reference the properties for givenName & Surname in order to concatenate them as strings. Otherwise you are trying to add 2 user objects together and will get an error.
Additional Info:
If this were me I would write this to be more concise. However, considering you are relatively new to PowerShell, I'd just make one recommendation. In the loop you don't need to get the user account multiple times, something like the below should work and be a little faster.
Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase 'ou=Users,ou=Test,dc=Sample,dc=Com' |
Select-Object SamAccountName |
Export-Csv -Path 'c:\Scripts\AllUsersSamaccountname.CSV' -NoTypeInformation
$file="c:\Scripts\AllUsersSamaccountname.CSV"
(Get-Content $file | Select-Object -Skip 1) | Set-Content $file
$Users = (Import-Csv -Path "c:\Scripts\AllUsersSamaccountname.CSV" -Header "AccountName")
foreach($User in $Users)
{
$ADUser = Get-ADUser -Identity $User.AccountName -Properties 'extensionAttribute1','givenName','Surname'
$extensionAttribute1 = ($ADUser.givenName + '.' + $ADUser.Surname)
$ADUser.extensionAttribute1 = $extensionAttribute1
Set-ADUser -Instance $ADUser
}
Get-ADUser -Filter * -SearchBase 'ou=Users,ou=Test,dc=George,dc=Com' |
Select-Object extensionAttribute1 |
Export-Csv -Path 'c:\Scripts\new-AllUserinfo6.CSV' -NoTypeInformation

Get-ADUser error, Name is not a parameter for filter

I have a powershell script to get administrators account details from the Active Directory but I am encountering this error. Sorry Im quite new to PowerShell.
Get-ADUser : Invalid type 'System.Object[]
Parameter name:name
At line:1 char:1
GetADUser -Filter {Name -eq $Admin} -Properties * | Select-Object DisplayName, ...
CategoryInfo : Invalid Argument: (:) [Get-ADUser], ArgumentException
FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
The following is my script:
PROCESS{
$path = Split-Path -parent "$CSVReportPath\*.*"
$pathexist = Test-Path -Path $path
If ($pathexist -eq $false)
{New-Item -type directory -Path $path}
$reportdate = Get-Date -Format ddmmyyyy
$csvreportfile = $path + "\ALLADUsers_$reportdate.csv"
$Admin = (Get-ADGroupMember -Identity Administrators | select-object Name
Foreach( $i in $Admin){
Get-ADUser -Filter {Name -eq $Admin} -Properties * | select-object DisplayName, samaccountName, Enabled,
Created, LastLogonDate | sort-object -Property LastLogonDate |
}
Export-Csv -Path $csvreportfile -NoTypeInformation
}
You should use $i as that's the variable you declared foreach item in $Admin. Next, use double quotes for the filter and single quotes around the variable.
Get-ADUser -Filter "Name -eq '$i'" -Properties *

Delete the disabled accounts since 90 days based on custom attribute value

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.

How To Ignore Error In Powershell Script (ErrorAction: SilentlyContinue not suppressing error)

I have a Powershell script that lists all the users/groups in the local administrators group for all computers in a designated OU in Active Directory.
The script works perfectly locally (if I run it against the local machine only) but when I run it against remote machines, it technically works but it throws a consistent error that I don't know how to filter out.
Here is the script (NOTE: must be running from ActiveDirectory PS console to use Get-ADComputer):
Get-ADComputer -SearchBase 'OU=ou01,dc=domain,dc=local' -Filter 'ObjectClass -eq "Computer"' `
| ForEach-Object {
Get-WmiObject win32_groupuser -cn $_.name -ErrorAction SilentlyContinue `
| Where-Object { $_.groupcomponent -match 'administrators' } `
| ForEach-Object -ErrorAction SilentlyContinue {[wmi]$_.partcomponent } `
| Select-Object __SERVER,Caption
} | Format-Table -Property * -AutoSize
Here are the results (correct result is in first line, error below that):
__SERVER Caption
-------- -------
workstation_name workstation_name\Administrator
Cannot convert value "\\workstation_name\root\cimv2:Win32_Group.Domain="DOMAIN",Name="Domain Admins"" to type "System.Management.ManagementObject". Error: "Not found "
At line:1 char:306
+ Get-ADComputer -SearchBase 'OU=ou01,dc=domain,dc=local' -Filter 'ObjectClass -eq "Computer"' | ForEach-Object { Get-WmiObject win32_groupuser -cn $_.name -ErrorAction SilentlyContinue | Where-Object { $_.groupcomponent -match 'administrators' } | ForEach-Object -ErrorAction SilentlyContinue {[wmi]$_. <<<< partcomponent } | Select-Object __SERVER,Caption } | Format-Table -Property * -AutoSize
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
I have unsuccessfully tried to use -ErrorAction SilentlyContinue, is there another way to suppress this message? Not sure what I am missing.

Filter Managedby Powershell

Below are my current attempts to pull AD groups whose managedby equal names like "ML...". I keep getting errors so I wanted to know why I am unable to filter managedby with "-like" when I can filter managedby "-eq $..." variables. I tried making a variable $name = "ML*" so that I can perform {managedby -eq $name} but still had no luck.
I mostly get error like:
Operator(s): The following: ''Eq', 'Ne'' are the only operator(s) suppor
ted for searching on extended attribute: 'ManagedBy'.
and so forth because "-eq" is only accepted for some filters I have done. When I use -eq I get these errors:
Import-Module : The following error occurred while loading the extended type dat
a file:
Microsoft.PowerShell, C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\ActiveD
irectory\ActiveDirectory.Types.ps1xml : File skipped because it was already pres
ent from "Microsoft.PowerShell".
Microsoft.PowerShell, C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\ActiveD
irectory\ActiveDirectory.Types.ps1xml : File skipped because it was already pres
ent from "Microsoft.PowerShell".
At J:\\ManagedbyEqualsML.ps1:1 char:14
+ Import-Module <<<< ActiveDirectory
+ CategoryInfo : InvalidOperation: (:) [Import-Module], RuntimeExc
eption
+ FullyQualifiedErrorId : FormatXmlUpateException,Microsoft.PowerShell.Comm
ands.ImportModuleCommand
The term 'Get-adgroup' is not recognized as the name of a cmdlet, function, scri
pt file, or operable program. Check the spelling of the name, or if a path was i
ncluded, verify that the path is correct and try again.
At J:\\ManagedbyEqualsML.ps1:53 char:27
+ $MLgroupAll = Get-adgroup <<<< -Properties managedby, enabled, name -filter
{managedby -eq $name}
+ CategoryInfo : ObjectNotFound: (Get-adgroup:String) [], CommandN
otFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Here are my codes where I attempted to find Owners that have the name ML*
Import-Module ActiveDirectory
$name = "ML*"
#Attempt 1
$MLgroups = Get-adgroup -Properties managedby, enabled, name -filter * | Select name, managedby
foreach ($group in $MLgroups){
if ($group.managedby -like "ML*"){
write-host $group.name + $group.managedby}
}
#Attempt 2
$Mgroups = get-adgroup -Properties name, managedby -filter *
foreach ($groups in $Mgroups){
# here get the group name and use the "managedBy attribute to retrieve the user object
# grou naem
$gname = $_.Name
$manager=Get-AdUser $_.ManagedBy
$MangerName = $manager.DisplayName
if ($managerName -like "ML*"){
write-host $gname + $managerName}
}
#Attempt 3
$exportlist = "C:\Temp\managedby.txt"
Clear-Content $exportlist
$Header = `
"Group ID Name" + "|" + "ManagedBy"
$Header | Out-File $exportlist -Append
$list = get-adgroup -properties name, managedby -filter {managedby -like "ML_*"} `
| Select name, managedby | Export-CSV $exportlist -NoType -Delimiter '|'
#Attempt 4
$MLgroupAll = Get-adgroup -Properties managedby, enabled, name -filter {managedby -like $name}
foreach ($group in $MLgroupAll) {
write-host $group.name + $group.managedby}
UPDATE: if i try to changed my $name variable it still doesn't work and gives another error.
$MLgroupAll = get-adgroup -Properties managedby, enabled, name -filter {managedby -eq $name}
foreach ($group in $MLgroupAll) {
$managed = $group.managedby
if ($managed -like "ML*"){
write-host $group.name + $group.managedby }
}
ERROR:
Get-ADGroup : Identity info provided in the extended attribute: 'ManagedBy' coul
d not be resolved. Reason: 'Cannot find an object with identity: 'ML*' under: 'D
C=we,DC=dirsrv,DC=com'.'.
#Paul: here is my error still:
Here is an example that works for me (orienting myself at your last try):
get-adgroup -filter * -Properties managedby | % {
if($_.managedby -like "CN=ML*"){
write-host $_.name + $_.managedby
}
}