Array of files, LastWrite Time

Hi, I’m making a script that in theory should be simple, but apparently is more complex than that.
I have a folder (source) with some xml files, hal of them have a name that begins with “030”, the other half begins with “150”. I have to select the last edited file whose name beins with “030” and copy it to another folder (destination).

My first idea was cicle through every file and if it contains “030” in the name add it to an array (Brescia), next I would check the file in that array with the LastWrite Time and copy it’s path.

However when I chekc filePath i get the path of my .ps1 file, so something must be off

$send = "C:\Source"
$receive = "C:\Destination"
$Brescia =@()

$search_results = Get-ChildItem -Path $send | Where-Object { ((! $_.PSIsContainer))}
foreach ($file in $search_results) {
    if($file.Name -match "030"){
        
   $Brescia + $file
 }
}

$lastfile = gci $Brescia | sort LastWriteTime | select -last 1
$filePath =$lastfile.FullName
Write-Output $filePath

Copy-Item $filepath -Destination $receive

Thank you in advance for your help

I think you meant to use += in your loop. However, that’s a bad practice because it doesn’t scale well, and a better way to add the results of a foreach loop to an array is to use:

$Brescia = foreach () {...}

You also have a problem with your -match because ‘030’ will match anywhere in the filename, not just at the start. To match the start only, you should use the start of string anchor ^.

All that said, you’re over complicating it. This is all you need to get the file you want:

Get-ChildItem -Path $send -Filter '030*' | 
    Sort-Object LastWriteTime | 
        Select-Object -Last 1
1 Like

Thank you so much, it works perfectly and it is much easier