Don
Don

Reputation: 13

Unlocking an AD user with Powershell

I’m new to Powershell and am struggling to make a script work. I’ve read many articles here on Overflow and elsewhere and don’t see what I’m doing wrong. Any help would be appreciated.

I'm trying to create a script that will unlock an AD user remotely while I'm logged-on to may computer as a local admin. Here's my script:

Import-module Activedirectory
New-PSSession  -ComputerName <Remote ComputerName> -Credential
    <domain admin credential>
Import-Module Activedirectory
Unlock-ADAccount
Read-host “Press any key”

I try to execute this from my computer logged-on as a local admin, but pass domain admin credentials. The script is run as an administrator in Powershell. After I enter my domain password and indicate which user I want to unlock, the message I get is: “Insufficient access rights to perform the operation”.

If I run this code interactively in Powershell, line by line, it will unlock the account. If I run a script asking only to see if the user is locked, it will give me an answer. If I run the above script from my computer logged-on as the domain admin, it will run and unlock the user.

I don’t understand why it will not run when I’m logged-on as local admin, given that I’m passing domain admin credentials. Any help would be appreciated.

Upvotes: 1

Views: 9285

Answers (2)

Adrian Rodriguez
Adrian Rodriguez

Reputation: 192

Although you could create a PSSession, if you have RSAT installed and have access to the ActiveDirectory module there is no need to do that. Instead, just use the credential parameter on each AD cmdlet. For instance, to unlock a user account using alternate credentials, use the following:

Unlock-ADAccount -Identity username -Credential (get-credential)

Upvotes: 0

Frode F.
Frode F.

Reputation: 54891

You're creating a PSSession, but not using it. Try something like this (untested):

$computer = "test1"
$cred = Get-Credential
$user = Read-Host User to unlock
$sess = New-PSSession -ComputerName $computer -Credential $cred
Invoke-Command -Scriptblock { param($ADuser) Import-Module Activedirectory; Unlock-ADAccount -Identity $ADuser } -ArgumentList $user -Session $sess
Read-host “Press any key”

Upvotes: 1

Related Questions