I collected bits and pieces of code about gMSA accout password. There are few articles mentioning how to get password but none of articles verifies fetched password. I created new GMSA account and specified my user and computer when I run script as -PrincipalsAllowedToRetrieveManagedPassword. I fetch password, convert it and try to start cmd.exe as elevated user. I got error:
Start-Process : This command cannot be run due to the error: The user name or password is incorrect.
Starting process as another local user, works, no problem in code. Here is code:
$username = "gTest01";
$gmsa = Get-ADServiceAccount -Identity $username -Properties 'msDS-ManagedPassword';
$mp = $gmsa.'msDS-ManagedPassword';
($mp | ForEach-Object ToString X2) -join ' ';
# Decode the data structure using the DSInternals module. Returns DSInternals.Common.Data.ManagedPassword object
$managedPasswordObj = ConvertFrom-ADManagedPasswordBlob $mp;
# Get credentials object
$sspwd = ConvertTo-SecureString $managedPasswordObj.CurrentPassword -AsPlainText -Force;
$startWithElevatedRights = "cmd.exe";
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username, $sspwd);
$ps = Start-Process -PassThru -FilePath powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ', $startWithElevatedRights, ' -Wait -verb runas}'
What is wrong with code?
I found answer. Problem is with username. GMSA users are domain accounts and domain must be specified as part of user name "domain\user".
Creating interactive process fails with error "Logon failure: the user has not been granted the requested logon type at this computer".
It is different problem.
Related
Basically I want to switch user in powershell in the same window (dont want to open a new one).
$username = "xxxxx"
$password = ConvertTo-SecureString "xxxxx" -AsPlainText -Force
$creds = New-Objet System.Management.Automation.PSCredential $username,$password
Start-Process powershell.exe -NoNewWindow -Credential $creds
But instead of launching powershell in same window it launches it in a new window which doesnt even work I cant type anything into its just a blinking cursor.
First things first, try to describe what you need to do in detail since the approach you're using might be misguided. Are you just trying to run commands as a different user within a script? If so, use the methods described here : https://www.itdroplets.com/run-a-command-as-a-different-user-in-powershell/
I particularly like the start-job method which I use sometimes, example:
#Shows who is the current user
whoami
""
$username = "DOMAIN\USER"
$password = ConvertTo-SecureString "PASSWORD" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential $username,$password
$GetProcessJob = Start-Job -ScriptBlock {
#Shows who is the current user, in this case it's the user you provided credentials for. Everything in this scriptblock will run in his context.
whoami
} -Credential $Credential
#Wait until the job is completed
Wait-Job $GetProcessJob | Out-Null
#Get the Job results
$GetProcessResult = Receive-Job -Job $GetProcessJob
#Print the Job results
$GetProcessResult
If you truly just want to just launch another powershell.exe process as another user,
the only way I know of would be to simply start the new process and exit the first one after that command, this way you have only the new window running as the user provided.
$username = "DOMAIN\USER"
$password = ConvertTo-SecureString "PASSWORD" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential $username,$password
Start-Process powershell.exe -Credential $creds ;Exit
Im using in PS the next command:
"Password" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
This generate a Key that im saving as "Key.txt" file
Now i want to decrypt that password using this:
$password = Get-Content password.txt (or just copy-pasting the key)
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username,($password | ConvertTo-SecureString)
BUT...
how i supose to add that to this...
$EmailFrom = "MyMail#gmail.com"
$EmailTo = "MayMail#gmail.com"
$Subject = "Test"
$Body = "this is a Test"
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("My_USer", "My_Password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
I want to add it as My_Password, of course i should add a variable $password that comes from the Key.txt file for example, but then...?
Nope, storing in plain text is not good at all, but if you are not concerned about that then it's there.
You have other options, with secure / encrypted files and Windows CredMan:
Quickly and securely storing your credentials – PowerShell
To get a credential object we can either manually create one or use the Get-Credential cmdlet to prompt for the account details:
$Credential = Get-Credential
To store the credentials into a .cred file:
$Credential | Export-CliXml -Path "${env:\userprofile}\Jaap.Cred"
And to load the credentials from the file and back into a variable:
$Credential = Import-CliXml -Path "${env:\userprofile}\Jaap.Cred"
Invoke-Command -Computername 'Server01' -Credential $Credential {whoami}
Securely Store Credentials on Disk
Allow multiple users to access credentials stored using export-clixml
How to run a PowerShell script against multiple Active Directory domains with different credentials
PowerShell Credentials Manager
CredMan.ps1 is a PowerShell script that provides access to the Win32 Credential Manager API used for management of stored credentials.
https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Credentials-d44c3cde
And modules to use
https://powershellgallery.com/packages/BetterCredentials
https://powershellgallery.com/packages/CredentialManager
https://powershellgallery.com/packages/IntelliTect.CredentialManager
First we save the credentials
"Password123" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File C:\key.txt -NoNewline
Then we can use it just like this :
$SMTPClient = New-Object Net.Mail.SmtpClient("SomeServer", 587)
$SMTPClient.Credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist ThisIsAUserName ,($(Get-Content C:\key.txt) | ConvertTo-SecureString)
And we can check to make sure it loaded correctly like this :
$SMTPClient.Credentials | select username, password
The output looks like this
UserName Password
-------- --------
ThisIsAUserName Password123
I'm trying to do the following script:
$EP = ExecutionPolicy
$Username = 'backup'
$Password = Get-Content 'C:\SecureString.txt' | ConvertTo-SecureString
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $Password
Import-Module VMware.DeployAutomation, ConfluencePS
if ($EP -eq 'Unrestricted') {
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted -Force
}
Set-ConfluenceInfo -BaseURI 'https://confluence.my.company' -PromptCredentials -Credential $Cred
Get-ConfluencePage
The problem is that even passing the variable with user and password it's still prompting me the authentication window and i didn't find any way to disable or avoid it.
Am I doing in the correct way?
thanks in advance.
Since i was using both -PromptCredentials and -Credential the windows was prompted regardless it already had user and password, so the solution was about to remove -PromtCredentials command.
Set-ConfluenceInfo -BaseURI 'https://confluence.my.company' -Credential $Cred
PS C:\Windows\system32> $creds = Get-Credential
cmdlet Get-Credential at command pipeline position 1 Supply values for
the following parameters: Credential
PS C:\Windows\system32> $ses = New-PSSession -ComputerName WIN-O4VC136J0E2 -Credential $creds
New-PSSession : [WIN-O4VC136J0E2] Connecting to remote server
WIN-O4VC136J0E2 failed with the following error message : The user
name or password is incorrect. For more information, see the
about_Remote_Troubleshooting Help topic. At line:1 char:8
+ $ses = New-PSSession -ComputerName WIN-O4VC136J0E2 -Credential $creds
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession],
PSRemotin gTransportException
+ FullyQualifiedErrorId : LogonFailure,PSSessionOpenFailed
The credentials I used are the same ones I used to login manually. Is there something else I am doing wrong? I've tried several different ways and never can seem to login.
Try the following, works very nicely with either a domain account or local account:
# Enter your pass and stores it securely:
$SecureString = Read-Host -AsSecureString 'Enter your password ' | ConvertFrom-SecureString | ConvertTo-SecureString
# Users you password securly
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "MyLoCalMachine\MyUserID",$SecureString
# Sets yous credentials to be used
$RemoteConn = New-PSSession -ComputerName $ts -Credential $MySecureCreds -Authentication default
I'm working on some automation in our test environment where we have powershell scripts to join a windows client to either a domain or a workgroup.
I'm having trouble trying to move a windows 7 client from a domain to a workgroup, in the case where the client's machine account doesn't exist in the domain.
Here is the code:
$User = administrator
$Password = ConvertTo-SecureString "<password>" -AsPlainText -Force
$DomainCred = New-Object System.Management.Automation.PSCredential $User, $Password
remove-computer -credential $DomainCred -force -passthru -verbose
This is the error that is returned:
VERBOSE: Performing operation "Remove-Computer" on Target "localhost".
Remove-Computer: This command cannot be executed on target computer ('xxx')
due to following error: No mapping between account names and security IDs was done.
At line :1 char:16
+ remove-computer <<<< -credential $DomainCred -force -passthru -verbose
+ CategoryInfo : InvalidOperation: (xxx:String) [Remove-Computer],
InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.Powershell.
Commands.RemoveComputerCommand
However, if I try this using the GUI (Computer Properties, Advanced system settings, Computer Name , Change...), it prompts for credentials and succeeds.
How would I replicate this operation into the powershell command so that it can be done pragmatically?
Try Add-Computer, like this (untested):
Add-Computer -WorkgroupName "WORKGROUP" -Force
AFAIK the only difference between Add-Computer and Remove-Computer is that Remove-Computer also disables the computer account, which would probably give you this error since the computer account doesn't exist.
I have two options.
Option 01
$Workgroup = "CL-01" #IF you want to add computer to domain edit here(Domain name)
$Password = "Password" | ConvertTo-SecureString -asPlainText -Force
$Username = "$Workgroup\Username"
$Credential = New-Object System.Management.Automation.PSCredential($Username,$Password)
Add-Computer -WorkGroup $Workgroup -Credential $credential
Restart-Computer -Force
Option 2 and why Option 2 Storing a password in a script is not such a favorable option so I suggest taking up option 2
$Workgroup = "CL-01"#IF you want to add computer to domain edit here(Domain name)
$Password = Read-Host -Prompt "Enter password for $user" -AsSecureString
$Username = "$Workgroup\Username"
$credential = New-Object System.Management.Automation.PSCredential($Username,$Password)
Add-Computer -WorkGroup $Workgroup -Credential $credential
Restart-Computer -Force
Note: Run the all the Scripts as Administrator!!
Hope this will help!! Cheers!!