Reputation: 1289
I currently have a script that successfully uses this method to remotely connect to a server and use Invoke-Command to run some tasks:
$c = Get-Credential
$computername = "server.fqdn"
$session = New-PSSession -ComputerName $computername -Authentication CredSSP -Credential $c
Doing this, I am prompted for a username and password of the account I want to run. I enter it and it works.
What I'd like to be able to do is instead of being prompted for the credentials when the script executes, I'd like it to automatically use the credentials that I store in a text file somewhere (or at least use the password this way). This is because I need to schedule the script to run from outside the server.
There is another thread that seems to hit pretty close to what I'm trying to do. Using a text file and convert-securestring. I don't quite understand how I can use this method using New-PSSession. Perhaps there is another way altogether.
So far I have the below code.
$username = "domain\username"
$password = cat C:\scripts\password.txt | convertto-securestring
$c = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
$computername = "server.fqdn"
$session = New-PSSession -ComputerName $computername -Authentication CredSSP -Credential $c
I am still prompted for a username and password and get the error:
convertto-securestring : Input string was not in a correct format
My password is in the text file. It's just something like password123. The password works until I try to use the text file.
Upvotes: 1
Views: 4101
Reputation: 72612
I'an not going to correct your code but here is the way I use to store password on some of my servers. The first time the code run, it asks for a password, and then stores it crypted in the file, the next times the password is read from the file. Be careful the password can be found fron the file content, it's not readable for us but it may be a security concern.
$passwordFile = "C:\scripts\password.txt"
$username = "domain\username"
# First time create password file
if (! (Test-Path $passwordFile))
{
Read-Host -AsSecureString | convertfrom-securestring | out-file $passwordFile
}
$password = Get-Content $passwordFile | convertto-securestring
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
Upvotes: 1