Saturday 13 October 2012

Run PowerShell script with different credentials

I was trying to run a PowerShell script with different credentials and for some reason it wasn't quite working.
This is what I was trying to do:
$secpass = ConvertTo-secureString "password" -asPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential ("username",$secpass)

start-process powershell.exe -Credential $cred -ArgumentList  ".\Install.ps1 -serverfile .\servers.txt " 
I would get this error:
Start-Process : This command cannot be executed due to the error: Logon failure: unknown user name or bad password.
The thing is that I had used the credentials to do an invoke-command and they worked fine.
invoke-command -Credential $cred -ComputerName $server -ScriptBlock { Invoke-Expression "C:\temp\Install.ps1 -serverfile c:\temp\servers.txt" } 
So I did a bit of investigating:
PS C:\temp> $cred.GetNetworkCredential()
UserName Password Domain
username password
Which lead me to two questions:
  1. Where did I expect the domain to come from if I've not passed it in?
  2. Why did it work before?
At any rate, the solution is fairly obvious:
$secpass = ConvertTo-secureString "password" -asPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential ("domain\username",$secpass)

start-process powershell.exe -Credential $cred -ArgumentList  ".\Install.ps1 -serverfile .\servers.txt " 
So now we get:
PS C:\temp> $cred.GetNetworkCredential()
UserName Password Domain
username password domain
The script now runs fine

1 comment:

  1. > 1. Where did I expect the domain to come from if I've not passed it in?

    It comes from the username. The username string is in the format 'domain'\'domain-username'. E.g. facebook\mark.zuckerberg

    Also, there's a cmdlet called Get-Credential which will prompt for user/password without having the password stored as clear text anywhere.

    ReplyDelete