Bootstrap FreeKB - PowerShell - Connect to a remote server using New-PSSession
PowerShell - Connect to a remote server using New-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.

 

It's probably a good idea to print a warning message if the connection failed and then exit.

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

if (-not $pssession) {
    Write-Warning "Failed to connect to $server with ID $xid - Got the following Exception:"
    Write-Warning $Error[0]
    exit
}

 

Or like ths, using try and catch.

try {
    $pssession = New-PSSession -ComputerName server1.example.com -Credential JohnDoe -ErrorAction Stop
}
catch {
    Write-Warning "Failed to connect to $server with ID $xid - Got the following Exception:"
    Write-Warning $Error[0]
    exit
}

 

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 -InstanceId $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 835907 in the box below so that we can be sure you are a human.