代码之家  ›  专栏  ›  技术社区  ›  Doug

使用PowerShell中的WinSCP检索过去一小时内修改的文件

  •  1
  • Doug  · 技术社区  · 8 年前

    我正在使用PowerShell脚本从远程目录检索文件。我只想检索在最后一小时内修改过的文件。我可以使用以下代码获取最新的文件:

    $directoryInfo = $session.ListDirectory($remotePath) 
    
    $latest = 
        $directoryInfo.Files | 
        Where-Object { -Not $_.IsDirectory } | 
        Sort-Object LastWriteTime -Descending | 
        Select-Object -First 1 
    

    我认为我需要在 Where-Object 子句,但我不知道正确的格式。例如

        Where-Object { -Not $_.IsDirectory and <created/modified within the last hour> } 
    

    我该怎么做?有更好/更简单的方法吗?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Frode F.    8 年前

    扩展您的当前 where -块检查是否 LastWriteTime 大于(更新) datetime -表示前一小时的对象。前任:

    $lasthour = (Get-Date).AddHours(-1)
    
    $directoryInfo = $session.ListDirectory($remotePath) 
    
    $latest = $directoryInfo.Files | 
    Where-Object { (-Not $_.IsDirectory) -and ($_.LastWriteTime -gt $lasthour) } | 
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1 
    
        2
  •  0
  •   Martin Prikryl    7 年前

    如果要下载最近一小时内创建/修改的所有文件,请使用:

    $directoryInfo = $session.ListDirectory($remotePath) 
    
    $limit = (Get-Date).AddHours(-1)
    
    $recentFiles = 
        $directoryInfo.Files | 
        Where-Object { (-Not $_.IsDirectory) -And ($_.LastWriteTime -Gt $limit) }
    
    foreach ($fileInfo in $recentFiles)
    {
        $sourcePath = [WinSCP.RemotePath]::EscapeFileMask($fileInfo.FullName)
        $session.GetFiles($sourcePath, $localPath + "\*").Check()
    }
    

    一些官员 WinSCP .NET assembly examples 用于生成代码: