Upload file to SFTP using PowerShell

前端 未结 4 1331
心在旅途
心在旅途 2020-12-12 20:48

We were asked to set up an automated upload from one of our servers to an SFTP site. There will be a file that is exported from a database to a filer every Monday morning an

4条回答
  •  眼角桃花
    2020-12-12 21:26

    There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.

    Here is an example using Posh-SSH:

    # Set the credentials
    $Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
    $Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)
    
    # Set local file path, SFTP path, and the backup location path which I assume is an SMB path
    $FilePath = "C:\FileDump\test.txt"
    $SftpPath = '/Outbox'
    $SmbPath = '\\filer01\Backup'
    
    # Set the IP of the SFTP server
    $SftpIp = '10.209.26.105'
    
    # Load the Posh-SSH module
    Import-Module C:\Temp\Posh-SSH
    
    # Establish the SFTP connection
    $ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
    
    # Upload the file to the SFTP path
    Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath
    
    #Disconnect all SFTP Sessions
    Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
    
    # Copy the file to the SMB location
    Copy-Item -Path $FilePath -Destination $SmbPath
    

    Some additional notes:

    • You'll have to download the Posh-SSH module which you can install to your user module directory (e.g. C:\Users\jon_dechiro\Documents\WindowsPowerShell\Modules) and just load using the name or put it anywhere and load it like I have in the code above.
    • If having the credentials in the script is not acceptable you'll have to use a credential file. If you need help with that I can update with some details or point you to some links.
    • Change the paths, IPs, etc. as needed.

    That should give you a decent starting point.

提交回复
热议问题