1

I have some file with different extension. Like this files

file123_A1.que
file456_B2.que
file123_00_A1.pro
file890_11_C2.pro

I want to copy the file by lastwritetime. But I don't want to copy the file if the file already has .pro, even the file is the lastwritetime. For the example, after sort the file by lastwritetime, the file that will be copied is file123_A1.que , but the that file name already has .pro by identify the 2 last file name A1. So in this case, I need to copy the other file. My expectation I will not copy a file if the file has the same 2 last name with different extension file (ex: file123_A1.que and file123_00_A1.pro the same 2 last file name. I will not copy this file file123_A1.que)

Anyone can give idea please. Thank you I tried this

$Sel_JobFolder = "D:\601"
$JobFolder = @(Get-ChildItem "$Sel_JobFolder\*.que" | Sort-Object LastWriteTime)[0] | 
ForEach-Object { Copy-Item -path $_.FullName -destination .\ -force}
0

1 Answer 1

1

One approach you could take is:

  • Get all files with Get-ChildItem and sort by extension in a descending manner. So this means .que will come before .pro files. We can use Sort-Object here to sort a calculated property which extracts the extension with System.IO.Path.GetExtension(), also ensuring we set Descending = $true to sort in descending order.
  • Add files to a hash table, where the key is the last item from splitting the filename by "_" e.g. key will become A1 from file123_A1. The idea here to replace .que files with .pro files if found.
  • Iterate the hash table and copy the latest file. If a .pro file was found, then it will be copied instead of the .que file. If no .pro file was found, then we copy the .que file instead.

Demo:

$directory = "D:\601"

# sort files by extension in descending order
$files = Get-ChildItem -Path $directory | Sort-Object -Property @{Expression = {[System.IO.Path]::GetExtension($_)}; Descending = $true}

# add files to hashtable. .que will be updated by .pro if found
$ht = @{}
foreach ($file in $files)
{
    $key = $file.BaseName.Split("_")[-1]
    $ht[$key] = $file.FullName
}

# copy files here
foreach ($entry in $ht.GetEnumerator())
{
    Copy-Item -Path $entry.Value -Destination .\
}

Which will copy the following files to your current working directory .\:

D:\file456_B2.que
D:\file890_11_C2.pro
D:\file123_00_A1.pro

Here we can see file123_A1.que was excluded from the copying, because file123_00_A1.pro replaced it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.