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
Related
Just some notes:
The issue that is being faced does not happen on every machine, only 1 in 20
I know it is not a powershell issue, but need to know from a health perspective what could cause this
The machine allows a connection with an Admin account over the PS Port, but after that the machine does not see the rights of the account
If I pass the Credentials using a Get-Credential rather than a PS Credential Object, it works however this is not an acceptable solution as the script it being wrapped in an MSO Runbook
Code being used for Credentials:
$Username = "domainname\userid"
$Password = "P#s4w0rd1!" | ConvertTo-SecureString -AsPlainText -Force
$mycreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $Password
Code for the PSSession:
$Session1 = New-PSSession -ComputerName WorkstationNAme #Connects to the computer
Invoke-Command -Session $Session1 -ScriptBlock {
$FreeDrive = (68..90 | %{$L=[char]$_; if ((gdr).Name -notContains $L) {$L}})[0] #Grabs the first available Drive Letter
$execDriveLocation = New-PSDrive -Name $FreeDrive -PSProvider FileSystem -Root $Using:Variable1 -Credential $using:mycreds -Persist #Creates temporary mapped drive
}
Error Returned on the affected machines:
The specified network password is not correct
+ CategoryInfo : InvalidOperation: (D:PSDriveInfo) [New-PSDrive], Win32Exception
+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand
+ PSComputerName : computername
Any thoughts or suggestions?
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 am using the PSCredential Object to authenticate a command, which I need to be run as a different user.
I get the following on the powershell cli.
> whoami
dmn1\srveikafka
> $secpasswd = ConvertTo-SecureString "mypassword" -AsPlainText -Force
> $mycreds = New-Object System.Management.Automation.PSCredential ("srveizookeeper", $secpasswd)
>
> $sess = new-pssession -computername remotecomputer.xyz.com -credential $mycreds
> invoke-command -session $sess -scriptblock {whoami}
dmn1\srveizookeeper
But when I run these same commands as a powershell script I get this error.
new-pssession : [remotecomputer.xyz.com] Connecting to remote server remotecomputer.xyz.com failed with the following
error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
At C:\workstation\add_zookeeper_spn.ps1:13 char:9
+ $sess = new-pssession -computername remotecomputer.xyz.com -credential $mycreds
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At C:\workstation\add_zookeeper_spn.ps1:14 char:25
+ invoke-command -session $sess -scriptblock {whoami}
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
What am I getting wrong or missing?
You might need to include the domain as part of the username in the credential constructor:
$mycreds = New-Object System.Management.Automation.PSCredential ("dmn1\srveizookeeper", $secpasswd)
I pass in credentials to the script via the env injector (note this works for me with Invoke-Command) and try to run Start-Job but jenkins doesn't like it:
$user = $ENV:user
$pass = $ENV:pass
write-output (cat env:username)
write-output (cat env:user)
write-output (cat env:pass)
$pass = $pass | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList ($user), $pass
Start-Job -Credential $cred -ScriptBlock {'test'}
write-output (get-job | Receive-Job)
get-job | remove-job
This is the error I get (confirmed username and password are correct, when I run this script from the console with the same creds it works)
Started by user ME
[EnvInject] - Loading node environment variables.
Building in workspace C:\Program Files (x86)\Jenkins\jobs\myjob\workspace
[workspace] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Windows\TEMP\hudson1723222179976241861.ps1'"
MYJENKINSSRV$
correctdomain\correctuser
correctPassword
Id Name PSJobTypeName State HasMoreData Location
-- ---- ------------- ----- ----------- --------
1 Job1 BackgroundJob Failed False localhost
[localhost] An error occurred while starting the background process. Error
reported: Access is denied.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTran
sportException
+ FullyQualifiedErrorId : -2147467259,PSSessionStateBroken
Finished: SUCCESS
i've had issues with credentials at times with PowerShell, i can usually fix it by using this:
$username = Username
$password = Password
$cred = New-Object -TypeName System.Management.Automation.PSCredential ($username, $password)
$Credentials = Get-Credential $cred
Basically entering the credentials into Get-credentials, then using that for credentials.
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!!