【问题标题】:Posh-SSH PowerShell How to get filename and status, and add line to log filePosh-SSH PowerShell 如何获取文件名和状态,并将行添加到日志文件
【发布时间】:2021-12-23 13:19:58
【问题描述】:

我正在尝试将文件复制到 SFTP 服务器,我使用 posh shh,如果它已成功移动,则我获取文件名并在日志文件中添加新行,否则我添加文件未移动或文件不在源目录中的行。 我了解如何将行复制并添加到日志文件中,但我无法在此脚本中引入正确的逻辑。

请在下面查看我的代码:

# SFTP Upload of Inventory From CSV files to WPEngine SFTP. Requires installation of Posh-SSH 
# Install-Module -Name Posh-SSH (https://github.com/darkoperator/Posh-SSH)
 
# Set the credentials
$Password = ConvertTo-SecureString 'almighty1992' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('sftpuser', $Password)
 
# Set local file path and SFTP path
$FilePath1 = "D:\TEST.txt"

$SftpPath = '/shared/'
 
# Set the Hostname of the SFTP server
$SftpServer = '192.168.1.215'
 
# Load the Posh-SSH module
#Import-Module Posh-SSH
 
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpServer -Credential $Credential -AcceptKey -Port 22
 
# Upload the files to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -Localfile $FilePath1 -RemotePath $SftpPath -Overwrite

 
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

Add-Content D:\LOG.TXT "Test" 

我不知道如何添加的代码。 如果我理解正确,我需要检查源目录中是否存在该文件。

#检查源文件是否存在 Test-Path -Path D:\TEST.txt -PathType Leaf

列出复制文件后的 sftp 目录文件 $FilePath = Get-SFTPChildItem -sessionID $SFTPSession.SessionID -path $SftpPath

#对于每个文件 ForEach ($LocalFile in $FilePath) {

if($LocalFile.name -eq "." -Or $LocalFile.name -eq ".." )
{
      Write-Host "Files Ignored!"
}
else
{
    Write-Host $LocalFile
    Get-SFTPFile -SessionId $SFTPSession.SessionID -LocalPath $LocalPath -RemoteFile $localfile.fullname 

强制 }

}

【问题讨论】:

    标签: powershell logging status get-childitem posh-ssh


    【解决方案1】:

    从 SFTP 会话中获取文件列表

    $Files = (Get-SFTPChildItem -SessionId $Session.SessionId -Path "$sftpRemotePath") | Select-object Name,FullName,Length | Sort-Object FullName
    

    过滤 /。和/..

    $msgFiles = $Files | where-object {$_.FullName -ne "/." -and $_.FullName -ne "/.."}
    

    将文件添加到日志中,每个文件后用新行分隔

    $filelist = $msgFiles | Foreach-Object " ${($_.Name)`n"}
    

    最后将文件列表添加到日志文件中

    Add-Content -value $filelist -Path $logfile
    

    注意:根据需要更改变量。

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 2020-08-31
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      相关资源
      最近更新 更多