gpt4 book ai didi

PowerShell脚本将文件而不是子文件夹复制到SFTP并在完成后移动到子文件夹

转载 作者:行者123 更新时间:2023-12-02 23:34:36 25 4
gpt4 key购买 nike

我正在使用以下脚本将文件从本地文件夹复制到 SFTP。上传文件后,我想将文件移动到子文件夹。我只想上传 C:\Users\Administrator\Desktop\ftp 中的文件文件夹,而不是其他子文件夹中的文件。

param (
$backupPath = "C:\Users\Administrator\Desktop\ftp\moved"
)

# Load the Assembly and setup the session properties
try
{
# Load WinSCP .NET assembly
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"

$session = New-Object WinSCP.Session

$filelist = Get-ChildItem C:\Users\Administrator\Desktop\ftp

# Connect And send files, then close session
try
{
# Connect
$session.Open($sessionOptions)

$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

foreach ($file in $filelist)
{
$transferResult = $session.PutFiles("C:\Users\Administrator\Desktop\ftp\$file", "/", $False, $transferOptions)
foreach ($transfer in $transferResult.Transfers)
{
Write-Host "Upload of $($transfer.FileName) succeeded"
Move-Item $transfer.FileName $backupPath
}
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}

exit 0
}
# Catch any errors
catch
{
Write-Host "Error: $($_.Exception.Message)"
exit 1
}

此时,如果我运行脚本 下的所有文件搬家 文件夹也会通过SFTP文件夹上传,我只需要上传 ftp根目录下的文件即可。文件夹。

我想我需要在这里更改这一行,但不确定如何更改它。
$filelist = Get-ChildItem C:\Users\Administrator\Desktop\ftp 

最佳答案

要跳过文件夹添加 -File切换到 Get-ChildItem (正如@Scepticalist 已经评论过的那样):

$filelist = Get-ChildItem -File C:\Users\Administrator\Desktop\ftp 

虽然您可以用更少的代码实现相同的效果,但如果您让 WinSCP 迭代文件(并跳过文件夹):
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
$transferOptions.FileMask = "|*/" # Exclude the folders

$transferResult = $session.PutFiles(
"C:\Users\Administrator\Desktop\ftp\*", "/", $False, $transferOptions)
foreach ($transfer in $transferResult.Transfers)
{
Write-Host "Upload of $($transfer.FileName) succeeded"
Move-Item $transfer.FileName $backupPath
}

而且您不需要任何 Get-ChildItem称呼。

以上基本上是WinSCP文章 Moving local files to different location after successful upload中的代码,只需一个 exclusion of subfolders .

但请注意,您的代码(与文章相反)没有成功上传的测试。因此,您甚至会移动无法上传的文件。确保添加 $transfer.Error -eq $Null测试。
foreach ($transfer in $transferResult.Transfers)
{
# Success or error?
if ($transfer.Error -eq $Null)
{
Write-Host "Upload of $($transfer.FileName) succeeded, moving to backup"
# Upload succeeded, move source file to backup
Move-Item $transfer.FileName $backupPath
}
else
{
Write-Host "Upload of $($transfer.FileName) failed: $($transfer.Error.Message)"
}
}

关于PowerShell脚本将文件而不是子文件夹复制到SFTP并在完成后移动到子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58758410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com