Powershell 输入PSSession with-Credential在脚本块中时仍提示输入凭据

Powershell 输入PSSession with-Credential在脚本块中时仍提示输入凭据,powershell,scriptblock,Powershell,Scriptblock,我有一个脚本,可以使用Enter-PSSession自动将用户登录到远程PowerShell会话。我使用新对象System.Management.Automation.PSCredential创建-Credential。如果它不在ScriptBlock中,则效果非常好。当我把它放在脚本块中时,它会在尝试连接时提示我输入凭据,我不知道为什么 如何使它在脚本块中工作 $userADPW = "password" $userAD = "john" $servip = "Server2K81.hom

我有一个脚本,可以使用Enter-PSSession自动将用户登录到远程PowerShell会话。我使用新对象System.Management.Automation.PSCredential创建-Credential。如果它不在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

请确保您理解:此解决方法将在该进程的“startinfo”中保留(编码的)密码,直到它关闭为止——因此该机器上的任何东西都可以读取密码(并可能解密密码)


不能将
PSCredential
对象传递到命令行。命令行参数必须是文本,而不是.NET对象。如果在-runas参数中使用John的凭据创建自定义委托会话,这不是会容易得多吗?@mjolinor,我该怎么做?这里有一些说明
$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