1

我有一个 WinSCP PowerShell 脚本,可以下载服务器上的最新文件。我想调整它以下载服务器上每种文件类型的最新文件。

将每个文件的扩展名命名为filename.txt( example.al-> al.txt) 的奖励积分。这是我的代码:

try
{
    # Connect
    $session.Open($sessionOptions)

    # Get list of files in the directory
    $directoryInfo = $session.ListDirectory($remotePath)

    # Select the most recent file
    $latest =
        $directoryInfo.Files |
        Where-Object { -Not $_.IsDirectory } |
        Sort-Object LastWriteTime -Descending |
        Select-Object -First 1

    $extension = [System.IO.Path]::GetExtension($latest.Name)
    "GetExtension('{0}') returns '{1}'" -f $fileName, $extension

    # Any file at all?
    if ($latest -eq $Null)
    {
        Write-Host "No file found"
        exit 1
    }

    # Download the selected file
    $session.GetFiles($session.EscapeFileMask($remotePath + $latest.Name), $localPath + $extension).Check()

现在它将文件另存为.extension,我想要将其另存为extension.txt.

谢谢!

编辑:

尝试了这段代码,它下载了服务器上的每个文件:

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    # Get list of files in the directory
    $directoryInfo = $session.ListDirectory($remotePath)

    # Select the most recent file
    $latest = $directoryInfo.Files |
        Where-Object { -Not $_.IsDirectory } | 
        Group-Object Extension | 
        ForEach-Object { 
            $_.Group | Sort-Object LastWriteTime -Descending | Select -First 1
            $session.GetFiles($session.EscapeFileMask($remotePath + $_.Name), $localPath).Check()
    }

    $extension = [System.IO.Path]::GetExtension($latest.Name)
    "GetExtension('{0}') returns '{1}'" -f $fileName, $extension

    # Any file at all?
    if ($latest -eq $Null)
    {
        Write-Host "No file found"
        exit 1
    }

    # Download the selected file
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}
4

1 回答 1

1

第一部分很容易使用Group-Object. 使用它按扩展分组,并从每个组中拉出一个。

$latest = $directoryInfo.Files |
    Where-Object { -Not $_.IsDirectory } | 
    Group-Object { [System.IO.Path]::GetExtension($_.Name) } | 
    ForEach-Object{ 
        $_.Group | Sort-Object LastWriteTime -Descending | Select -First 1
    }

接下来我们处理每个扩展王并下载。您可以在同一个循环中执行此操作,但我将它放在一个单独的循环中。还没有考虑单独的扩展。

$latest | ForEach-Object{
    $session.GetFiles($session.EscapeFileMask($remotePath + $_.Name), $localPath + $extension).Check()
}

我对你想要的扩展部分有点模糊,但为此我们也需要循环中的扩展逻辑。

$latest | ForEach-Object{
    $extension = ([System.IO.Path]::GetExtension($_.Name)).Trim(".")
    $session.GetFiles($session.EscapeFileMask($remotePath + $_.Name), "$localPath\$extension.txt" ).Check()
}
于 2015-10-01T19:27:05.947 回答