简体   繁体   中英

How to copy a file to other directory sort by first received using PowerShell?

I have some file in a folder, I want to copy one file which is the first received.

$Sel_JobFolder = "D:\Testing"
$PickJob = Get-ChildItem -Path "$Sel_JobFolder\*.que" | Sort-Object LastWriteTime
$count = 1
$GetJob = Get-Random -InputObject $PickJob -Count $count
Write-Output "Selected Job: $GetJob"

copy-Item $GetJob -Destination "C:\\File"

Updated

This what I need, and It works

$PickJobs = @(Get-ChildItem "$Sel_JobFolder\*.que" | Sort LastWriteTime)[0] | % { Copy-Item -path $_.FullName -destination $("C:\Process") -force}

here's a very simple demo of how to work with a list of files in newest-first order. [ grin ]

$SourceDir = $env:TEMP
$Filter = '*.log'

$FileList = Get-ChildItem -LiteralPath $SourceDir -Filter $Filter -File |
    Sort-Object -Property LastWriteTime -Descending

foreach ($FL_Item in $FileList)
    {
    'doing stuff to the files in newest-first order ...'
    '    {0}' -f $FL_Item.Name
    '    {0}' -f $FL_Item.LastWriteTime
    '=' * 50
    }

truncated output ...

doing stuff to the files in newest-first order ...
    Itunes_AlbumAutoRating_Disable.ps1_2019-08-19.log
    2019-08-19 12:21:25 PM
==================================================
doing stuff to the files in newest-first order ...
    Itunes_Default-Rating_Set.ps1_2019-08-16.log
    2019-08-16 12:47:38 PM
==================================================

[*...snip...*] 

==================================================
doing stuff to the files in newest-first order ...
    Grouping-Strings-List_2019-07-31.log
    2019-07-31 12:35:17 PM
==================================================
doing stuff to the files in newest-first order ...
    Itunes_Genre-Cleanup.ps1_2019-07-30.log
    2019-07-30 12:36:03 PM
==================================================
doing stuff to the files in newest-first order ...
    Genre-List_2019-07-30.log
    2019-07-30 12:36:03 PM
==================================================

Is it random or first received?

If it's a random, try using get-random from array ,

A, b, c | get-random -count 1

So your first scope is to create the array of the pool to be picked by the random function.

For the second option,

Your code is fine, but you need to sort it.

Or simply combine them both as per your need.

  • EDIT

Try to modify the second line to :

$PickJob = (Get-ChildItem -Path "$Sel_JobFolder\*.que" | Select-Object -Property name,LastWriteTime) | Sort-Object LastWriteTime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM