0

I've written the following short script to remove stale objects in my Active Directory

$csvFilePath = "C:\path\to\file.csv"
Import-Csv -Path $csvFilePath | ForEach-Object {
    $username = $_.SamAccountName
    Remove-ADUser -Identity $username
}

I can delete user accounts in Active Directory Users and Computers ('ADUC') by right clicking and deleting but not by using the Remove-ADUser cmdlet. I don't understand where I've gone wrong.

I was expecting the script to be remove the users in "C:\path.csv" to be removed from my on-premise Active Directory but I receive the following error:

Remove-ADUser : Access is denied CategoryInfo : PermissionDenied: (ACCOUNT I WANT TO DELETE:ADUser) [Remove-ADUser], UnauthorizedAccessException FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.UnauthorizedAccessException,Microsoft.ActiveDirectory.Management.Commands.RemoveADUser

I've tried running the script in a standard and elevated terminal. I've also tried running PowerShell with the same privileged user account I can use to delete accounts in using ADUC.

2
  • It's safe to assume you're running PowerShell as the same user that can delete objects in ADUC right? If so, try running PowerShell elevated (run as admin) Commented Jul 11, 2023 at 13:36
  • I'm logged into my device using my standard account. When I log on to PowerShell as a different user (i.e. my privileged account) it still shows to be running as my standard account. I can only run with elevated rights using my standard credentials. Commented Jul 11, 2023 at 13:46

1 Answer 1

0

The cause of my issue was the fact that I wasn't using PowerShell in the same user context as I am when I can delete accounts from AD Users and Computers and when I was, that account couldn't access the directory the script I was pointing at.

When I logged into PowerShell in the correct user context, I modified my script to call the file from C:\ and it worked.

$csvFilePath = "C:\file.csv"
Import-Csv -Path $csvFilePath | ForEach-Object {
    $username = $_.SamAccountName
    Remove-ADUser -Identity $username
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.