0

I had created a PSCredential with the inline script and was able to access the credential until the PowerShell session which created the credential was open. When I have closed and reopened PowerShell to run the script again, I was not able to access $TFSAdminCred:

$UserID = "xyz"
$PswdFile = "\\Server1\TFSencrypt$\Pswd.txt"
$KeyFile = "\\Server1\TFSencrypt$\AES.txt"

$Key = New-Object byte[] 16
[System.Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | Out-File $KeyFile
$Key = Get-Content $KeyFile

$Pswd = "password" | ConvertTo-SecureString -AsPlainText -Force |
        ConvertFrom-SecureString -Key $Key | Out-File $PswdFile

$TFSAdminCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserId, (Get-Content $PswdFile | ConvertTo-SecureString -Key $Key)
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Sam
  • 279
  • 3
  • 9

1 Answers1

0

To persist variables for re-use you can export them to disk and import on Powershell start, or you can use powershell profiles to do that for you.

To export variable do

$var | export-clixml 'path'

To import

$var = import-clixml 'path'

to import with profile just add import to your powershell profile, to access your profile do notepad $profile from your PS prompt

4c74356b41
  • 69,186
  • 6
  • 100
  • 141
  • As suggested, i tried to add up inline script in the end $TFSAdminCred = Export-Clixml -Path "\\server\sharedpath\cred.txt" and when i wanted to use it – Sam Mar 07 '17 at 14:46
  • As suggested, i tried to add up inline script at the end $TFSAdminCred = Export-Clixml -Path "\\server\sharedpath\cred.txt" and when i wanted to use it to stop a website, ran this $TFSAdminCred = Import-Clixml -Path "\\server\sharedpath\cred.txt" Invoke-Command -computername xyz.com -credential $TFSadminCred -scriptblock {import-module webadministration; stop-website -name "Websitename"} Works manually! But when i tried to automate it, throws the error "Key not valid for use in specified state." Am i missing anything? – Sam Mar 07 '17 at 14:56
  • try this: https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/export-clixml and this: https://blogs.msdn.microsoft.com/timid/2013/03/08/fun-with-pscredentials/ – 4c74356b41 Mar 07 '17 at 20:43
  • Just realized that i have missed to inform you that, I am trying to import these credentials on remote server and per this link http://stackoverflow.com/questions/40029235/save-pscredential-in-the-file?rq=1 it clearly states that it cannot be used on remote server. Which helped me to get an idea that alteast the XML serialization is not the solution. Henceforth, i am still in lookout for a way to run automated scripts on remote server from my build machine. Also appreciated your efforts to help me out in this. – Sam Mar 08 '17 at 17:43