Enter-PSSession with -Credential still prompts for credentials when inside a ScriptBlock

StackOverflow https://stackoverflow.com/questions/22801417

  •  25-06-2023
  •  | 
  •  

Question

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
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top