Skip to content

Instantly share code, notes, and snippets.

@lawndoc
Created August 15, 2024 17:06
Show Gist options
  • Save lawndoc/4cc958c37363aa9ce9a7a5c7d54a7681 to your computer and use it in GitHub Desktop.
Save lawndoc/4cc958c37363aa9ce9a7a5c7d54a7681 to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Enable PowerShell Remoting on a remote host and connect to a PsSession
.DESCRIPTION
This script requires PsExec.exe in ./Tools local to where the script is run from. It will utilize PsExec to enable
Powershell Remoting, and then it will use PsSession to enter an interactive session. When the PsSession is closed, the
script will use PsExec again to disable Powershell Remoting.
.EXAMPLE
.\ShellOn.ps1 Computer01
.PARAMETER Computer
The name of the computer to connect to. The credentials you enter must have local admin privileges on the computer.
.NOTES
PsSession includes a bug that requires it to be run as a subprocess in order to be run synchronously from a script.
The subprocess workaroud requires you to type 'exit' twice to exit from the remote PsSession and clean up the script.
See the below link for details on the PsSession bug:
https://stackoverflow.com/questions/69678580/enter-pssession-session-block-the-calling-process-until-user-types-exit
#>
param (
[Parameter(Mandatory)]$Computer
)
$SessionName = "vsec_$pid"
$Cred = Get-Credential
Write-Host "[+] Enabling PsRemoting on $Computer..."
./Tools/PsExec.exe -i -s -u $Cred.UserName -p $Cred.GetNetworkCredential().Password \\$Computer powershell -c "Enable-PSRemoting"
Write-Host "--------------------------------------------------------------------"
Write-Host "[!] IMPORTANT: you'll need to submit 'exit' twice to exit PSSession AND PowerShell"
Write-Host "[+] Entering PSSession..."
$null = Invoke-Command -InDisconnectedSession -ComputerName $Computer -SessionName $SessionName -Credential $Cred -ScriptBlock {}
powershell.exe -NoExit -NoProfile {
param($Computer, $SessionName)
$Session = Get-PsSession -ComputerName $Computer -Name $SessionName
Enter-PsSession -Session $Session
} -Args $Computer, $SessionName
Write-Host "--------------------------------------------------------------------"
Write-Host "[+] Session ended. Disabling PsRemoting on $Computer..."
./Tools/PsExec.exe -i -s -u $Cred.UserName -p $Cred.GetNetworkCredential().Password \\$Computer powershell -c "Disable-PSRemoting"
Write-Host "[+] Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment