SSH from PowerShell with Posh-SSH

For more information on Posh-SSH:  https://github.com/darkoperator/Posh-SSH

This module is for Windows PowerShell 3.0 or above. It is compiled for .NET Framework 4.5.

Install-Module -Name Posh-SSH

Here’s a simple script that grabs credentials from a file.  See this other article for more on password management.  It uses the credentials to open a new SSH session to the remote computer and execute the pwd command and returns the results of that command.  Then, it closes the SSH session.

$computerName = "computername.domain.com"
$userId = "myUserId"
$pwd = Get-Content "$PSScriptRoot\$userId.Pw.txt" | ConvertTo-SecureString
$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $userId, $pwd

try {
    "Attempting SSH to $computerName"
    $sshSession = New-SSHSession -ComputerName $computerName -Credential $creds -AcceptKey -ConnectionTimeout 10 -ErrorAction Stop
    $sessionId = $sshSession.SessionId
    "Session $sessionId opened."
    $command = "pwd"
    "Command: {0}" -f $command
    $sshOut = (Invoke-SSHCommand -SessionId $sessionId -Command $command).Output
    "Results: '{0}'" -f $sshOut
    Remove-SSHSession -SessionId $sessionId | Out-Null
    "Session $sessionId closed."
}
catch {$_.exception.Message}