Error In Powershell Execution for removal a domain computer from Domain

Hi,

I am using below powershell script to removal machine from domain, however i am getting error. When i use the same credentials manually it works.

$User = "Admin User"
$PWord = ConvertTo-SecureString -String "Password" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
Remove-Computer -UnjoinDomaincredential $Credential -PassThru -Verbose -Restart -Force > c:\temp\output.txt

I am getting below error.

**Remove-Computer : Failed to unjoin computer 'USLVLXXXDSP0001' from domain 'one.ads.bms.com' with the following error message: Access is denied.**
**At line:4 char:1**
**+ Remove-Computer -UnjoinDomaincredential $Credential -PassThru -Verbos ...**
**+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~**
**    + CategoryInfo          : OperationStopped: (USLVLXXXDSP0001:String) [Remove-Computer], InvalidOperationException**
**    + FullyQualifiedErrorId : FailToUnjoinDomain,Microsoft.PowerShell.Commands.RemoveComputerCommand**

Do you really have the password for an administrative user in plain text in your script? If the answer is “yes” - that’s a really bad idea.

Assumed you always use the same profile on the same computer to do such an administrative task you could use Get-Credential instead and save the resulting object with Export-Clixml in the file system. That’d still not a very secure way but at least it would avoid to have a password in plain text in a script file.

A more professional way would be to use the new module

Here you have a short introduction:

Thanks for your reply, i will secure the password with password vault or using your idea later once my script works.

but as of now i am getting access denied when i execute it but working fine when i use GUI and remove machine from domain.

Since I’m not using such techniques I don’t have experiences.

It may help the (re-)read the according help completely including the examples.