Bootstrap FreeKB - PowerShell - Disconnect from a remote server using Remove-PSSession
PowerShell - Disconnect from a remote server using Remove-PSSession

Updated:   |  PowerShell articles

New-PSSession can be used to connect to a remote server.

$pssession = New-PSSession -ComputerName server1.example.com -Credential JohnDoe

 

When running the command, there should be a pop-up that asks for your password.

 

If you are ok with storing username and password in the PowerShell script, you could do something like this, and then you won't be prompted for your password.

$password = ConvertTo-SecureString "SuperSecretPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("JohnDoe", $password )

$pssession = New-PSSession -ComputerName server1.example.com -Credential $cred

 

The Get-PSSession command should now return something like this.

 Id Name      ComputerName         ComputerType    State         ConfigurationName     Availability
 -- ----      ------------         ------------    -----         -----------------     ------------
  1 WinRM1    server1.example.com  RemoteMachine   Opened        Microsoft.PowerShell     Available

 

And you can issue more than one command. Notice in the prior commands that the output of the New-PSSession command is being stored in a variable named $pssession. Printing the $pssession variable

Write-Host $pssession

 

Should return something like this. This really isn't all that useful.

[PSSession]WinRM1

 

PSSession contains certain keys, such as InstanceId. Printing the $pssession.InstanceId key

Write-Host Instance ID = $pssession.InstanceId

 

Should return the Instance ID.

Instance ID = 46d99d57-457f-4ba3-adf5-5922a083992a

 

This is much more useful, because then Remove-PSSession can be used to end the connection to the target server.

Remove-PSSession $pssession.InstanceId

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 5f52a9 in the box below so that we can be sure you are a human.