我有一个脚本,可以使用Enter-PSSession自动将用户登录到远程PowerShell会话。我使用 New-Object System.Management.Automation.PSCredential 创建 -Credential。如果它不在脚本块中,这很好用。当我把它放在脚本块中时,它会在尝试连接时提示我输入凭据,我不确定为什么。
我将如何使它能够在脚本块中工作?
$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"中,直到它关闭 - 因此该计算机上的任何内容都可以读取密码(并可能解密它)。
$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