Running an SSH command from PowerShell with Posh-SSH
Open an SSH session, run a command and close it from PowerShell with the Posh-SSH module.
The Posh-SSH module lets you open an SSH session from PowerShell, run a command in it, and close the session. The example below follows the approach described in SSH from PowerShell with Posh-SSH.
Installation
Install-Module -Name Posh-SSH
Example
$computerName = "sftp01.example.com"
$userId = "app_user"
$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}
The password is read from a file located next to the script ($PSScriptRoot). That file must contain a secure string, for example one produced with ConvertFrom-SecureString under the same Windows account.