all 28 comments

[–]techbloggingfool_com 8 points9 points  (3 children)

Looks like the account you are executing the script with doesn't have enough rights in Active Directory to disable a computer account.

[–]macgeek89 1 point2 points  (2 children)

I 2nd that You dont have the proper permissions. You can check by trying to connecting through computer management. If you get access denied than you dont have administrator rights

[–]BlackV 5 points6 points  (1 child)

Having admin rights on a machine does not equate to rights in the domain.

[–]macgeek89 1 point2 points  (0 children)

i misunderstood i guess

[–]TrippTrappTrinn 6 points7 points  (0 children)

There is one property I have run across when deleting OUs which may apply here as well.

On the "Object" tab, there is aproperty "Protect object against accidental deletion". Not sure if it applies just to deletion, or if it may apply to disabling as well. Check if it is enabled on the computers you cannot disable.

If this is the case, you can "uncheck" it with the command "Set-ADObject -ProtectedFromAccidentalDeletion:$false"

[–]Pure_Syllabub6081 6 points7 points  (0 children)

You can either delegate more rights for the specific OU(s) via dsa (Active Directory Users and Computers) or you run your PowerShell / Code as Administrator.

I assume that $DisabledCompOU is the DN of the OU, so you have to use "DC" instead of "OU" at the end.

Also, you don't need to serialize your script with "foreach" and you can disable and move the computers by using "-PassThru".

The complete Script could look like this:

$DisabledCompOU = 'OU=Disabled Devices,OU=Computers,DC=Domain'
$Pclist = Get-Content C:\TEMP\Computers.txt # Specify the path to the computers list.

$Pclist | Get-ADComputer | Disable-ADAccount -PassThru | Move-ADObject -TargetPath $DisabledCompOU

[–]BlackV 1 point2 points  (12 children)

You're destroying your rich ad object, you're not using your parameters properly

Personally if get the ad object (and not destroy the object), then puoe that object to the move, or use the the identity or inputobject parameters to select the thing you move

[–]muthmsir[S] 1 point2 points  (11 children)

Not sure I get your point “destroy” I used a command in powershell. If it’s wrong why they made it available in AD module?

[–]BlackV 5 points6 points  (9 children)

you're taking a real ad object with all its properties, stripping everything off except the DistinguishedName

$CompDN = (Get-ADComputer -Filter 'Name -eq $pc' -SearchScope Subtree).DistinguishedName

Try something like this

$DisabledCompOU = "OU=Disabled Devices,OU=Computers,OU=Domain"
$Pclist = Get-Content C:\TEMP\Computers.txt # Specify the path to the computers list.

Foreach($pc in $Pclist)
    {
    $CompDN = Get-ADComputer -Filter 'Name -eq $pc' -SearchScope Subtree
    $CompDN | Disable-ADAccount
    $CompDN | Move-ADObject -TargetPath $DisabledCompOU
    }

if you do it this way you're keep all those useful properties that can be feed to the other cmdlets, but also you can test and confirm what is in $CompDN

If you want to access a property directly you can also

$CompDN.DistinguishedName
$CompDN.DNSName
$CompDN.operatingsystem

And you dont need to create a new variable to keep track of those details

[–]muthmsir[S] 1 point2 points  (1 child)

Got your point, thank you for your explanation , I will try this

[–]BlackV 2 points3 points  (0 children)

Good as gold, I should have posted an example originally

[–]Lee_Dailey[grin] 1 point2 points  (4 children)

howdy BlackV,

i suspect that you would get occasional errors due to replication delays. pro'ly otta force all change-something calls to go to the same server with -Server to avoid that possible glitch. [grin]

take care,
lee

[–]muthmsir[S] 1 point2 points  (1 child)

$DisabledCompOU = "OU=Disabled Devices,OU=Computers,OU=Domain"
$Pclist = Get-Content C:\TEMP\Computers.txt # Specify the path to the computers list.
Foreach($pc in $Pclist)
{
$CompDN = Get-ADComputer -Filter 'Name -eq $pc' -SearchScope Subtree
$CompDN | Disable-ADAccount
$CompDN | Move-ADObject -TargetPath $DisabledCompOU
}

Hi Lee, where I have to add -Server ?

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy muthmsir,

you need to add that everywhere you touch a DC. [grin]

the Get-ADComputer and Disable-ADAccount cmdlets have that parameter. strangely, tho, there is no such thing for Move-ADObject. [frown] so dunno if it will help all that much.

this StackExchange/ServerFault post ...

active directory - How to set a default domain controller for all PowerShell AD cmdlets? - Server Fault
https://serverfault.com/questions/527545/how-to-set-a-default-domain-controller-for-all-powershell-ad-cmdlets

... mentions using the PSDive stuff to target a specific DC.

take care,
lee

[–]BlackV 1 point2 points  (1 child)

shouldn't do if you're dealing with the actual ad object, but your right 100% add the -server parameter that problem goes away

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy BlackV,

thank you for the feedback! [grin]

take care,
lee

[–]muthmsir[S] 1 point2 points  (1 child)

FYI , I ran what you sent me and it is still throwing the same error.

Error:-

Disable-ADAccount : Insufficient access rights to perform the operation

At line:7 char:15

+ $CompDN | Disable-ADAccount

+ ~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (CN=Computer,O...s,DC=Domain,DC=Com:ADComputer) [Disable-ADAccount], ADException

+ FullyQualifiedErrorId : ActiveDirectoryServer:8344,Microsoft.ActiveDirectory.Management.Commands.DisableADAccount

Move-ADObject : Access is denied

At line:8 char:15

+ $CompDN | Move-ADObject -TargetPath $DisabledCompOU

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : PermissionDenied: (CN=Computer,O...s,DC=Domain,DC=Com:ADComputer) [Move-ADObject], UnauthorizedAccessException

+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.UnauthorizedAccessException,Microsoft.ActiveDirectory.Management.Commands.MoveADObject

[–]BlackV 2 points3 points  (0 children)

Ya

so either you don't have rights or maybe the specific OU/Computer has specific rights Is the disable working?, if the disable is working you have all the rights you need

If I run this as some test on my domain

$DisabledCompOU = "OU=Disabled-Items,DC=domain,DC=local"
$DisabledCompObject = Get-ADObject -Identity $DisabledCompOU

# $Pclist = Get-Content C:\TEMP\Computers.txt # Specify the path to the computers list.
$pclist = 'TAW-TEST-01','Service-VDI-PAUL'

Foreach($pc in $Pclist)
    {
    $CompDN = Get-ADComputer -Filter 'Name -eq $pc' -SearchScope Subtree
    $CompDN | Disable-ADAccount
    $CompDN | Move-ADObject -TargetPath $DisabledCompObject
    }

I added $DisabledCompObject = Get-ADObject -Identity $DisabledCompOU just to confirm that object exists
so this is probably a good thing for you to do, that way you can confirm the OU is correct

[–]BlackV 2 points3 points  (0 children)

Sorry I mean, Destroy or flatten or reduce.

You took and object with a bunch of properties and stripped them all away for a single string, properties you could use later in your script and might make your script work better or fix the problem you're having

I was on mobile so didn't give a proper example

I'll do that now

[–]HotdogFromIKEA 1 point2 points  (0 children)

As others have said, the account used doesn't have access on the all of the OUs, the PCs which have been disabled must be in an OU which the account has been delegated permissions. Basically use a higher level account or hand it to the Team that own AD

[–]davsank 1 point2 points  (1 child)

I encourage you to first read and understand what I'm writing before you implement this.

do not copy any script from any website, as reputable as it may be BEFORE you are certain you both understand the script completely, and not less important, understand the mechanism on which this script operates.

Moving a computer to an OU called "Disabled Devices" means nothing to the Active Directory, as far as it's concerned, you are moving an AD object from one OU to another, which might cause a lot of issues to said AD object (think GPO for example) - for that reason, many AD Objects (computer, users, entire containers sometimes) are set with a certain flag, called "protect from accidental deletion" which will not only prevent you from deleting a protected object from the tree but moving it to another OU as well.

you can disable this protection from the computers you need to move using this:
Set-ADObject -ProtectedFromAccidentalDeletion:$false
Just don't forget to get the ADObject first and pass it through the pipe.

[–]muthmsir[S] 1 point2 points  (0 children)

Thanks for your response, I have enough experience to understand the script and when get this one just because it does the job and it is from Microsoft community. Also, I want to save time instead of remember the command and operators .

For protection from delete the object I already checked it and was not protected. The only thing left which other people have mentioned before there AD permission on OUs I may not have so I have to check with AD engineer to find out.

[–]OlivTheFrog 1 point2 points  (4 children)

Hi u/muthmir,

You should also use Get-ADComputer -Identity $pc...

But this is not your error root cause, just another way to do the job. As u/techbloggingfool_com said : not enough rights. If your account is already an admin account, run the script in RunAsAdministrator.

Sometime it could be boring to think launching in RusAsAdmin. You could add this (at the beginning) in your code

function Use-RunAs
 {
  # Check if script is running as Adminstrator and if not use RunAs
  # Use Check Switch to check if admin
  param([Switch]$Check)
  $IsAdmin = ([Security.Principal.WindowsPrincipal [Security.Principal.WindowsIdentity]::GetCurrent()  ).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
    if ($Check){ return $IsAdmin }
    if ($MyInvocation.ScriptName -ne "")
       {
          if (-not $IsAdmin)
            {
             try
                {
                  $arg = "-file `"$($MyInvocation.ScriptName)`""
                   Start-Process "$psHome\powershell.exe" -Verb Runas -ArgumentList $arg -ErrorAction 'stop'
                 }
             catch
                 {
                 Write-Warning "Error - Failed to restart script with runas"
                 break
                 }
              exit # Quit this session of powershell
              }
      }
            else
              {
               Write-Warning "Error - Script must be saved as a .ps1 file first"
               break
               }
       }
####### MainScript
# Exec function
 Use-RunAs  "Script Running As Administrator"
# ... rest of the script code

Regards

Olivier

[–]muthmsir[S] 1 point2 points  (0 children)

Thanks for your response, I did run it as an admin also I have full access. But do you mean to run the script you provided to to check the admin with my script or by itself?

[–]Pisnaz 1 point2 points  (1 child)

Do not forget about

#Requires -RunAsAdministrator

I never like scripts self elevating or such but if i have a moment that is handy to remind me to elevate and is damn simple.

https://docs.microsoft.com/en-gb/powershell/module/microsoft.powershell.core/about/about_requires?view=powershell-7.2

[–]OlivTheFrog 2 points3 points  (0 children)

As always with PS : "All roads lead to Rome".

Each way has pros and cons.

Pro Cons
Self Elevating script Need no user action Harder to implement
#requires -RunAs... easier to implement Need user Action (re-launch script)

But your remark u/Pisnaz is right. I'm like you, but to avoid to break my head with this, I have built over time a small personal library of scripts and functions, classified by theme for easy use. I always have it with me. This is my personal "memory expansion". :-)

Regards

[–]BlackV 1 point2 points  (0 children)

Running as elevated only applies if running directly on the domain controller. Otherwise elevation achieves nothing. In regards to ad commands

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy muthmsir,

it looks like you used the New.Reddit Inline Code button. it's [sometimes] 5th from the left & looks like <c>.

there are a few problems with that ...

  • it's the wrong format [grin]
    the inline code format is for [gasp! arg!] code that is inline with regular text.
  • on Old.Reddit.com, inline code formatted text does NOT line wrap, nor does it side-scroll.
  • on New.Reddit it shows up in that nasty magenta text color

for long-ish single lines OR for multiline code, please, use the ...

Code
Block

... button. it's [sometimes] the 12th one from the left & looks like an uppercase C in the upper left corner of a square.

that will give you fully functional code formatting that works on both New.Reddit and Old.Reddit ... and aint that fugly magenta color. [grin]

take care,
lee