Forum Discussion
dannytveria
Aug 26, 2021Brass Contributor
Disable and removal of Computer accounts
Hi, I made a script to disable old computer accounts. My Sysadmin asked me to disable after 180 days and remove them after a year. My goal is to disable computer accounts after 180 days and export...
- Sep 13, 2021
dannytveria
Aug 29, 2021Brass Contributor
farismalaeb
thanks for your help, but I goal is in 1 script to do both of the processes.
thanks for your help, but I goal is in 1 script to do both of the processes.
RGijsbersRademakers
Aug 29, 2021Iron Contributor
If you use the script provided by farismalaeb, you only need to add Get-BadPC -Days 365 -Action Delete on row 21 and save the file as a ps1 file.
function Get-BadPC{
param(
[parameter(mandatory=$true)]$Days,
[parameter(mandatory=$true)]
[ValidateSet('Delete','Disable')]$Action
)
$InactiveDate = (Get-Date).Adddays(-($Days))
$Computers_For_Action = Search-ADAccount -AccountInactive -DateTime $InactiveDate -ComputersOnly -SearchBase "DC=Test ,DC=local" | Where-Object {($_.distinguishedname -notlike "*,OU=Servers,*") -or ($_.distinguishedname -notlike "*,OU=Test,*") -or ($_.distinguishedname -notlike "*,OU=IT,*") -or ($_.distinguishedname -notlike "*,OU=Laptops,*") -or ($_.distinguishedname -notlike "*,CN=Computers,*")}
$Computers_For_Action | Export-Csv "C:\Users\Administrator\Downloads\$($Action)-$((Get-Date).ToString('dd-MM-yyyy')).csv" -NoTypeInformation -Encoding UTF8
switch ($action){
Disable {$Computers_For_Action | Disable-ADAccount }
Delete {$Computers_For_Action | Remove-ADComputer -Confirm:$False }
}
}
Get-BadPC -Days 180 -Action Disable
Get-BadPC -Days 365 -Action DeleteThen you can run the script from PowerShell by just running .\ScriptLocation\scriptname.ps1
You could also add some logging to the script with the Write-Log Function
function Write-Log([string[]]$Message, [string]$LogFile = $Script:LogFile, [switch]$ConsoleOutput, [ValidateSet("SUCCESS", "INFO", "WARN", "ERROR", "DEBUG")][string]$LogLevel)
{
$Message = $Message + $Input
If (!$LogLevel) { $LogLevel = "INFO" }
switch ($LogLevel)
{
SUCCESS { $Color = "Green" }
INFO { $Color = "White" }
WARN { $Color = "Yellow" }
ERROR { $Color = "Red" }
DEBUG { $Color = "Gray" }
}
if ($Message -ne $null -and $Message.Length -gt 0)
{
$TimeStamp = [System.DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss")
if ($LogFile -ne $null -and $LogFile -ne [System.String]::Empty)
{
Out-File -Append -FilePath $LogFile -InputObject "[$TimeStamp] $Message"
}
if ($ConsoleOutput -eq $true)
{
Write-Host "[$TimeStamp] [$LogLevel] :: $Message" -ForegroundColor $Color
}
}
}You will have some reference for later on which devices have been disabled and which are deleted.
- dannytveriaSep 12, 2021Brass Contributor
Maybe you saw that problem and know how to solve it?
I attached the error from the script