Powershell wont disable AD Service Accounts that were never logged into, why?

By using "!PowershellGPT" you have requested a response to the OP regarding their Powershell question. This bot is in testing.


It is possible that the accounts that have never been logged into may have certain attributes or settings that prevent them from being disabled through PowerShell. One way to troubleshoot this issue is to check the properties of these accounts and compare them with those of the accounts that were successfully disabled.

You can use the following script to check the properties of the accounts:

$ADuser = "ServiceAccountName" $result = Get-ADUser -Identity $ADuser -Properties *

Write-Host "Account Name: $($result.Name)" Write-Host "Enabled: $($result.Enabled)" Write-Host "Last Logon Time: $($result.LastLogonTimestamp)"

This will display the Name, Enabled status, and Last Logon Time of the account. Check if there are any differences in the properties of the accounts that were successfully disabled and those that were not.

If you find that the accounts have the same properties, you can try using the -Server parameter with the Get-ADUser cmdlet to specify the domain controller to use for the query. This can sometimes resolve issues with disabling accounts.

Another option is to use the Set-ADUser cmdlet instead of Disable-ADAccount to set the Enabled property to $false. This may work for accounts that cannot be disabled through the Disable-ADAccount cmdlet.

Here's an example script:

$ADuser = "ServiceAccountName" $result = Get-ADUser -Identity $ADuser

if ($result.LastLogonTimestamp -lt (Get-Date).AddYears(-2) -or !$result.LastLogonTimestamp) { Set-ADUser -Identity $ADuser -Enabled $false -WhatIf Write-Host "Account $($result.Name) disabled." -ForegroundColor Green } else { Write-Host "Account $($result.Name) has been logged into within the last 2 years and will not be disabled." -ForegroundColor Yellow }

This script checks if the LastLogonTimestamp property is older than 2 years or if it is null (meaning the account has never been logged into). If so, it disables the account using Set-ADUser. The -WhatIf parameter is used to show what would happen if the command were run, without actually modifying anything.

/r/bottesting Thread Parent