Home > OS >  Powershell - Spawn a remote interactive shell from script
Powershell - Spawn a remote interactive shell from script

Time:11-30

This is part of a homework assignment. As part of an administration script, one of the tasks is to open an interactive Powershell prompt on a remote computer using preset credentials from the script. Opening one from the regular interactive shell works fine, however opening one from a script has proven to be difficult.

I have tried the following:

$password = ConvertTo-SecureString -String "password" -AsPlainText -Force`
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "username", $password
$session = New-PSSession -Credential $credentials -ComputerName "remote-computer"
Enter-PSSession -Session $session

Doing this from an interactive shell works as expected and spawns an interactive prompt on the remote machine, however doing this from a script results in a non-responsive shell as it expects further input from the script.

If I attempt Start-Process -Wait -NoNewWindow -FilePath "powershell" or tell Start-Process to execute Powershell via cmd.exe after entering a remote Powershell session it opens a local instance instead.

CodePudding user response:

Possibly look into Invoke-Command with -Session & -ScriptBlock parameters. You'd still be using your PSSession and $Session variable, but would be passing your commands in a scriptblock to that PSSession.

CodePudding user response:

Invoke-Command works fine for me:

# Scriptblock to run in new Powershell process
$cmd = {
    param(
        $targ,
        $user,
        $pass
    )

$SecurePassword = ConvertTo-SecureString -String $pass -AsPlainText -Force -ErrorAction Stop
$CredentialObj = New-Object System.Management.Automation.PSCredential($User,$SecurePassword) -ErrorAction Stop

Enter-PSSession -ComputerName $targ -Credential $CredentialObj  | Invoke-Command -ScriptBlock {Set-Location -Path "C:\."}

}
# Supply credentials and target
$usertext = 'domain\username'
$pwtext = 'mypassword'
$Foundcomputer = 'targetcomputer'

#Launch new Ps process and invoke scriptblock
Start-Process powershell.exe -ArgumentList ("-noexit -command (Invoke-Command -ScriptBlock {$cmd} -ArgumentList $FoundComputer, "   $UserText   ","   $PwText   ")")
  • Related