Change a user password on remote domain in PowerShell - windows

I need to be able to allow users from a remote domain to change their password and I cannot install RSAT tools and the machine they will be working on.
I have tried an Invoke-Command passing domain admin credentials to run some code on a domain controller however I cannot get Invoke-Command to authenticate.
$InvUsername = "admin"
$InvPassword_Text = "adminpassword"
$InvPassword = ConvertTo-SecureString -AsPlainText $InvPassword_Text -Force
$InvCreds = New-Object System.Management.Automation.PSCredential -ArgumentList $InvUsername,$InvPassword
$InvSession = New-PSSession -ComputerName 'DC01.domain.co.uk' -Credential $InvCreds
New-PSSession -ComputerName 'DC01.domain.co.uk' -Credential $InvCreds
New-PSSession : [DC01.domain.co.uk] Connecting to remote server DC01.domain.co.uk failed with the following error message : The user name or password is incorrect.
The password is not incorrect BTW.

Do you need to create a new remote PowerShell session to do it? Are you able to contact one of the domain controllers directly?
You could try using .NET's DirectoryEntry and passing credentials. If you know the distinguishedName of the account:
$user = New-Object System.DirectoryServices.DirectoryEntry("LDAP://CN=user,DC=example,DC=com", $username, $password)
$user.Invoke("SetPassword","NewPassword123")
You may also have to tell it to explicitly connect through the LDAPS (LDAP over SSL) port like this:
$user = New-Object System.DirectoryServices.DirectoryEntry("LDAP://DC01.domain.co.uk:636/CN=user,DC=example,DC=com", $username, $password)
But that also assumes that LDAPS is setup correctly with a certificate your computer trusts.

Related

New-PSDrive as "anonymous" for remote share that has enabled "Network access: Let Everyone permissions apply to anonymous users"

How does one connect anonymously to an SMB share in powershell using New-PSDrive?
I've tried omitting the -Credential param but this seems to use the currently logged in user. This works when I test using a domain account, however the problem is for normal operation the currently logged in user is a local kiosk user for assigned access that the domain file server does not recognize.
I've also tried using the following, however it prompts for user input. As this is run as a scheduled task for background operation - this is unacceptable.
$Credentials = Get-Credential -UserName 'NTAUTHORITY\Anonymous Logon'
New-PSDrive -ErrorAction Stop -PSProvider "FileSystem" -Root "$RemoteFolder" -Name "$RemoteDriveLetter" -Credential $Credentials -Persist -Scope Global | Out-Null
I have enabled the local security policy option on the file server for "Network access: Let Everyone permissions apply to anonymous users".
How do I utilize the "anonymous" user connection with New-PSDrive?
-- edit --
I've also tried this
$Credentials = [pscredential]::Empty
New-PSDrive -ErrorAction Stop -PSProvider "FileSystem" -Root "$RemoteFolder" -Name "$RemoteDriveLetter" -Credential $Credentials -Persist -Scope Global | Out-Null
However, the output is:
>> TerminatingError(New-PSDrive): "The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: The specified network password is not correct"
The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: The specified network password is not correct
Anonymous mounts use an 'empty' user and password for the credential block so you can do the same.
This works for me and allows file creation on the share:
$User = " " # Create 'empty' username
$PWord = ConvertTo-SecureString -String " " -AsPlainText -Force
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
New-PSDrive -PSProvider "FileSystem" -Root "$RemoteFolder" -Name "$RemoteDriveLetter" -Credential $Credentials -Persist -Scope Global | Out-Null

Installing certificate under a different user causes Access Denied while not logged in to VM

I'm building a VM image in Azure through automation pipelines using PowerShell. One of the requirements is to install a certificate on the CurrentUser store for a specific user. When I am currently logged into the VM, I can run the following command through Azure Run Commands:
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$session = New-PSSession $env:ComputerName -credential $Credential
$command = {
param($certPassword, $filePath)
Import-PfxCertificate -FilePath $filePath -CertStoreLocation Cert:\CurrentUser\My -Password $certPassword
}
Invoke-Command -ScriptBlock $command -ArgumentList $certPassword,$filePath -Session $session
When I am not currently logged into the VM under that user, I get an Access Denied error. The error goes away as soon as I login to the machine again. If I run the pipeline while I'm logged into the VM, it succeeds.
What is different about PowerShell permissions while I am logged into the VM?

Logon failure: unknown username or bad password error on Windows Server 2012 R2 for Remote PS script execution

I am trying to run a powershell script from a TeamCity Windows Slave to another server for deploying my application.
This is BuildConfig:
username = "<username>"
$password = "<password>"
$secstr = New-Object -TypeName System.Security.SecureString;
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr;
Invoke-Command -ComputerName "<computer_name>" -Credential $cred -FilePath "deploy.ps1"
I am getting the following error.
following error message : Logon failure: unknown user name or bad password.
[13:57:52] [Step 1/1] For more information, see the about_Remote_Troubleshooting Help topic.
I have used the correct User name and password only.
I have also checked the Local User security policies. Am I missing something?
Is it just a paste error that missed the $ from username ?
Does the user name and password work fine outside the script ?
Are the variables being substituted in properly. Do the logs show ?
I’ve never used that construct to make a pscredential before. Is this one mentioned here not working.
https://pscustomobject.github.io/powershell/howto/PowerShell-Create-Credential-Object/

How to run powershell scriptblock as domain user?

I have a script block that I'm trying to make it run as a different domain user.
$Username = 'domain\test'
$Password = '1234'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName,$pass
Invoke-Command -ScriptBlock{
write-host "hello"
} -Credential $cred -ComputerName $env:COMPUTERNAME
When I run it I got the following error:
[test-pc] Connecting to remote server test-pc failed with the following error message : The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests.
Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the destination to analyze and configure the WinRM se
rvice: "winrm quickconfig". For more information, see the about_Remote_Troubleshooting Help topic.
Why the script is trying to authenticate locally and not against the DC ?
Thanks
If you don't actually want to run the script remotely, you can use Start-Process to run Powershell as another user, which will then execute your command/script as that user.
(See powershell command line help for full syntax options and examples)
# Using Get-Credential to illustrate, substitute with your own credential code
$cred = Get-Credential
# Run Command:
Start-Process -FilePath Powershell -Credential $cred -ArgumentList '-Command', 'Write-Host "Hello"'
# Run Script:
Start-Process -FilePath Powershell -Credential $cred -ArgumentList '-File', 'C:\folder\script.ps1'

How to create a local windows user account using remote powershell?

tried creating users with powershel.This worked fine for local machine. But how to create a local user account in a remote machine using remote powershell?
The script localwindows.ps1 is
$comp = [adsi]'WinNT://machinename,computer';
$user = $comp.Create('User', 'account4');
$user.SetPassword('change,password.10');
$user.SetInfo();
I tried the same thing through C# :
PSCredential credential = new PSCredential(userName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machinename", 5985, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
String file = "C:\\localwindows.ps1";
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(System.IO.File.ReadAllText(file));
pipeline.Commands.Add("Out-String");
// execute the script
Collection<PSObject> results = pipeline.Invoke();
}
This also works fine locally .But for remote computer its throwing exception "create :Access is denied ".
I was able to create a local user account in a remote computer using the following command :
Invoke-Command -ComputerName machineName -filepath c:\script.ps1 -credential $getcredential
The script is
$comp = [adsi]'WinNT://localhost,computer';
$user = $comp.Create('User', 'account11');
$user.SetPassword('change,password.10');
$user.SetInfo();
$user
Use the ADSI WinNT provider:
$username = "foo"
$password = "bar"
$computer = "hostname"
$prov = [adsi]"WinNT://$computer"
$user = $prov.Create("User", $username)
$user.SetPassword($password)
$user.SetInfo()
The powershell script invoke-Command executes any powershell script on a remote computer. You didn't say just how you use powershell to create the user, but as an example you write:
invoke-command -computername myserver {[ADSI]$server="WinNT://localhost";$HD=$server.Create("User","HD");$HD.SetPassword("H3lpD3>K");$HD.SetInfo()}
You can also execute your local powershell script remotely by using the -filepath parameter:
Invoke-Command -ComputerName MyRemoteServer -filepath c:\Scripts\DaScript.ps1
To enable remote commands you will have to enable winrm on the remote computer. you can do this by running
winrm quickconfig
On the remote computer.
If you have a PowerShell script to create a local user account locally on a server, then just simply use PSExec to run it on remote machines with administrative account
Invoke-Command works but you can also use Enter-PSSession -Computer to submit commands locally on a remote machine.
The following will prompt the user for the username and add them to the local Administrators group with no password:
$user = read-host 'What is the name of the local user you would like to add?'
net user /add $user
net localgroup Administrators /add $user
I don't know if the question is still relevant, but I have tried this out and found what needs to be fixed. When you create the directory entry object, use the following code
$objOu = New-Object System.DirectoryServices.DirectoryEntry("WinNT://$computer", $admin, $adminPass, "Secure")
The rest is the same.

Resources