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
Related
How to change this script so netrwork drive is still aviable after machine reboot?
$User = "user"
$PWord = ConvertTo-SecureString -String "password" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$net = $(New-Object -ComObject WScript.Network)
$net.MapNetworkDrive("r:", "\\name\othername")
Powershells way:
New-PSDrive -Name "R" -PSProvider FileSystem -Root "\\name\othername" -persist:$true -Scope Global
Use:
net use r: \\name\othername
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 return exit code from a powershell script that is executed on a remote machine. But, when I check ExitCode it has some random number.
What I'm doing wrong? In addition, is it possible to return the whole text?
my script
$proc = Start-Process -Filepath "$PSExec" -ArgumentList "\\$server -h -u $user -p $pass -d PowerShell $command" -PassThru -Wait
$proc.ExitCode
remote script
New-Item "c:\temp\1.txt" -type file -force
exit 123
UPDATE
$secureString = ConvertTo-SecureString $password -Force -AsPlainText #$password includes password in clear text
$cred = New-Object System.Management.Automation.PSCredential($usrName, $secureString)
$sess = New-PSSession -ComputerName $serverName -Credential $cred
$command = "`"C:\temp\1.ps1`""
$result = Invoke-Command -Session $sess -ScriptBlock {
Start-Process -Filepath "$PSExec" -ArgumentList "\\$server -h -u $usrName -p $password -d PowerShell $command" -PassThru -Wait
}
Can you use Invoke-Command as an alternative?
Example:
$session = New-PSSesson -ComputerName $serverName -Credential (Get-Credential)
$result = Invoke-Command -Session $session -ScriptBlock {
Start-Process ...
}
As an alternative to Get-Credential you can created a credential object and pass it via the -Credential paramter to Invoke-Command. Example:
$secureString = ConvertTo-SecureString $password -Force -AsPlainText #$password includes password in clear text
$cred = [System.Management.Automation.PSCredential]::new($usrName, $secureString)
$sess = New-PSSession -ComputerName $ComputerName -Credential $cred
Invoke-Command -Session $sess -ScriptBlock { ... }
$result should also include the ExitCode property, since Powershell Remoting serializes the remote object. I always suggest Powershell Remoting compared to the cmdlet specific ComputerName implementations. It uses a more standardized way (WsMan -> HTTP(S)). See this link for further details.
Hope that helps.
For your first approach, your issue is that when running psexec with the -d (don't wait) flag it returns the pid of the command that launched it, rather than waiting and returning the exitcode.
Altogether your process also could be optimized. First if you wanted to use psexec.exe, I don't see a reason for Start-Process since you are waiting and passing through. Just & $psexec ... would suffice.
However Moerwald's suggestion for using Invoke-Command is a great one. In your updated code, you are still running Start-Process and Psexec which are unnecessary. When you are invoking the command, you are already remotely running code, so just run the code:
$secureString = ConvertTo-SecureString $password -Force -AsPlainText
$cred = New-Object System.Management.Automation.PSCredential($usrName, $secureString)
$result = Invoke-Command -ComputerName $serverName -Credential $cred -ScriptBlock {
New-Item "c:\temp\1.txt" -type file -force
exit 123
}
Also, since it doesn't look like you are reusing the session, I dropped the saving the session to a variable. And it would also be better to replace all of the credential setup with a Get-Credential rather than passing plaintext passwords around (avoid the password ending up in a saved transcript). That would look like this:
$result = Invoke-Command -ComputerName $serverName -Credential (Get-Credential) -ScriptBlock {
New-Item "c:\temp\1.txt" -type file -force
exit 123
}
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!!