If you want to use SFTP with Powershell to transfer files, you can do this with the Posh-SSH module.
Table of Contents
Installation of SFTP with Powershell
To retrieve or copy data via Powershell using SFTP, you can use the Posh-SSH module. Installation is relatively simple on a standard Windows 11. Simply install the module with Install-Module and confirm the source as trustworthy.
Install-Module -Name Posh-SSH
If the following error message appears in older versions of Powershell and Windows, you might need to activate TLS 1.2 This is usually necessary in older environments.
Simply enter the following command in Powershell and try to install the module again.
#[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-Module -Name Posh-SSH
Connection setup
The connection is established with New-SFTPLocation and saved in a session variable. The credentials are queried in the process. However, they can also be saved to a file as described in the article Powershell – Passwort in einer Datei Abspeichern and used again here.
$SFTPSession = New-SFTPSession -ComputerName <IP oder DNS Name> -Credential (Get-Credential)
In our homelab environment we will connect to linux1.ad.hartiga.de
$SFTPSession = New-SFTPSession -ComputerName linux1.ad.hartiga.de -Credential (Get-Credential)
Commands
The connection should then be open. You can now use the following command via the session variable $SFTPSession.
- Get-SFTPLocation – Retrieve the current directory on the SFTP server
Get-SFTPLocation -SessionId $SFTPSession.SessionId
The upload and download is pretty much identical. The overwriting of existing files must be confirmed with the -Force parameter.
- Set-SFTPItem – Transferring a file to the SFTP server
- Get-SFTPItem – Download a file
#example to transfer files
Set-SFTPItem -SessionId $SFTPSession.SessionId -Path C:\Users\ahart\AppData\Local\Temp\test.txt -Destination /home/ah
#example to transfer files and force overwriting of existing file
Set-SFTPItem -SessionId $SFTPSession.SessionId -Path C:\Users\ahart\AppData\Local\Temp\test.txt -Destination /home/ah -Force
#example to get files
Get-SFTPItem -SessionId $SFTPSession.SessionId -Path /home/ah/test.txt -Destination C:\Users\ahart\AppData\Local\Temp
#example to transfer files and force overwriting of existing local file
Get-SFTPItem -SessionId $SFTPSession.SessionId -Path /home/ah/test.txt -Destination C:\Users\ahart\AppData\Local\Temp -Force
All commands can be found in the PowerShell Gallery from Posh-SSH.
If you want to learn more, please check out the video below.
Disconnect
At the end, you should disconnect your connection. This is done simply by using the Remove-SFTPSession command and specifying the session variable. A simple True should appear in response.
Remove-SFTPSession -SessionId $SFTPSession.SessionId
Find more Powershell commands here and the original version in German by Jörg Karsten is here.