0

I have a script that automatically logs a user into a remote PowerShell session using Enter-PSSession. I create the -Credential with New-Object System.Management.Automation.PSCredential. This works great if it is not inside a ScriptBlock. When I put it inside a script block it prompts me for credentials when it tries to connect and I am not sure why.

How would I make it so it works inside the ScriptBlock?

$userADPW = "password"

$userAD = "john"

$servip = "Server2K81.homelab.com"

$PassSec = ConvertTo-SecureString $userADPW -AsPlainText -Force

$credentialPS = New-Object System.Management.Automation.PSCredential ($userAD,$PassSec)

Start-Job -ScriptBlock {param($psip,$CredentialPS2) Start-Process powershell -Argumentlist '-noexit',"Enter-PSSession -ComputerName $psip -Credential $CredentialPS2" -passthru -Wait} -ArgumentList $servip,$credentialPS
  • 2
    You can't pass a `PSCredential` object into a command line. The command line arguments must be text, not .NET objects. –  Apr 02 '14 at 06:07
  • Wouldn't this be a lot easier if you created a custom delegated session using John's credentials in the -runas parameter? – mjolinor Apr 02 '14 at 11:21
  • @mjolinor,How would I do that? – John Smithman Apr 03 '14 at 00:13
  • Some instruction here http://blogs.msdn.com/b/taylorb/archive/2012/03/26/remote-administration-with-powershell-3-0-sessions-part-1.aspx – mjolinor Apr 03 '14 at 00:16

1 Answers1

2

To be sure you understand: This workaround will leave the (encoded) password in the "startinfo" for that process until it's closed -- so anything on that machine can read the password (and probably decrypt it).

$userADPW = "password"

$userAD = "john"

$servip = "Server2K81.homelab.com"

$PassSec = ConvertTo-SecureString $userADPW -AsPlainText -Force

$credentialPS = New-Object System.Management.Automation.PSCredential ($userAD,$PassSec)

Start-Job -ScriptBlock { 
   param($psip,$CredentialPS2) 
   Start-Process powershell -Argumentlist '-noexit',"&{
   `$Credential = New-Object System.Management.Automation.PSCredential '$($CredentialPS2.UserName)', (ConvertTo-SecureString '$(ConvertFrom-SecureString $CredentialPS2.password)')
   Enter-PSSession -ComputerName '$psip' -Credential `$Credential
  }" -passthru -Wait
} -ArgumentList $servip,$credentialPS
Jaykul
  • 15,370
  • 8
  • 61
  • 70