Powershell 脚本仅查找并复制文件夹中的最新文件

问题描述 投票:0回答:1

我在完成 powershell 脚本时遇到了一些麻烦。该脚本用于从 SFTP 服务器复制两个文件。这些文件位于一个目录中,该目录将被复制到共享文件夹以供查看和处理。这两个文件的名称将始终相同,但扩展名除外,扩展名每次都会增加一个随机数。文件1.120和文件2.130。

该脚本设置为将文件从目录复制到共享文件夹,以便适当的人员可以查看这两个文件。

• 这是从目录到共享文件夹的单向复制,复制时不能覆盖目录上的文件

• 还有第二个脚本每天运行,检查是否是该月的最后一个工作日,如果是,则会触发文件复制脚本

• 我希望脚本在目录中搜索两个硬编码文件并仅复制最新的文件 我在尝试像 robocopy 或类似的东西时遇到的问题是,一旦运行脚本就不再复制两个硬编码文件,而是复制当天上传的随机文件。

这是复制每个文件的循环。

# Get a list of files from the source folder
$files = Get-SFTPChildItem -SessionId $SessionID -Path "/path/to/dir/"

# Loop through each file and copy 
foreach ($file in $files) {
    if ($file.Name -match $file1BaseName -or $file.Name -match $file2BaseName) {
        $sourceFolder = Join-Path $sourceFolder $file.Name
        Get-SFTPItem -Path $file.FullName -Destination $destinationFolder -SessionId $SessionID -Force
        Write-Output "File $($file.BaseName) copied to $($destinationFolder)"
    }

if-else 语句复制错误文件的示例

# Get the most recently modified file from the source folder
$mostRecentFile = Get-SFTPChildItem -SessionId $SessionID -Path "/path/to/dir/" | Sort-Object -Descending -Property LastWriteTime | Select-Object -First 1

if ($mostRecentFile -ne $null) {
    $sourcePath = $mostRecentFile.FullName
    Get-SFTPItem -Path $sourcePath -Destination $destinationFolder -SessionId $SessionID -Force
    Write-Output "File $($mostRecentFile.Name) copied to $($destinationFolder)"
} else {
    Write-Output "No files were found in the source folder."
}
powershell filesystems sftp file-copying
1个回答
0
投票

这对我有用。

#Find the newest file for "test1"
$filesTest1 = Get-SFTPChildItem -SessionId $SessionID -Path $sourceFolder | 
Where-Object { $_.Name -like "$file1BaseName*" }
$newestFileTest1 = $filesTest1 | Sort-Object LastWriteTime -Descending | 
Select-Object -First 1

#Copy the newest "test1" file if found
if ($newestFileTest1 -ne $null) {
 $sourcePathTest1 = Join-Path $sourceFolder $newestFileTest1.Name
Get-SFTPItem -Path $newestFileTest1.FullName -Destination 
$destinationFolder -SessionId $SessionID -Force
Write-Output "Newest $file1BaseName file copied to $($destinationFolder)"
}
© www.soinside.com 2019 - 2024. All rights reserved.