locked
Computer Disable script RRS feed

  • Question

  • Hi all,

    Hoping someone would be able to give me some guidance here. I'm using the below script to automatically disable any computer accounts that have been inactive for 30 days and move it to a disabled computers OU. 

    I'm targetting our root computers folder which has multiple OUs with computer accounts in them. How could I exclude a sub OU from the below search? Thanks!

    Get-ADComputer -SearchBase "OU=Computers - ALL,DC=example,DC=com" -Properties Name,lastLogonDate,CanonicalName -Filter {lastLogonDate -lt $days} | Where-Object {$_.Enabled -eq $true} | ? {$_.DistinguishedName -like "*OU=Computers - ALL*"} | Set-ADComputer -Enabled $false
    Start-Sleep -s 30
    Get-ADComputer -SearchBase "OU=Computers - ALL,DC=example,DC=com" -Properties Name,lastLogonDate,CanonicalName -Filter {lastLogonDate -lt $days} | Where-Object {$_.Enabled -eq $false} | ? {$_.DistinguishedName -like "*OU=Computers - ALL,*"} | Move-ADObject -TargetPath 'OU=Computers - Disabled,DC=example,DC=com'

    • Moved by Bill_Stewart Wednesday, September 4, 2019 9:26 PM This is not "scripts on demand"
    Tuesday, April 23, 2019 12:58 PM

All replies

  • Hello,

    You can do a list with the OUs you need and then do a foreach...

    Tuesday, April 23, 2019 1:02 PM
  • I thought there might have been a shorter way, figured I'd ask anyway - thanks for your reply. 
    Tuesday, April 23, 2019 1:33 PM
  • Get-ADComputer -SearchBase 'OU=Computers - ALL,DC=example,DC=com' -Filter "Enabled -eq $true -and lastLogonDate -lt $days " | 
        Where-Object { $_.DistinguishedName -notlike '*excluded ou'} |
        Set-ADComputer -Enabled $false


    \_(ツ)_/

    Tuesday, April 23, 2019 1:47 PM