2

I am getting all wav files in the past 24 hours from one folder and putting them in another folder. I swear this worked for me a bit ago and wanted to add in some more conditional statements but now it is working. It is not creating a new folder for 'NewSounds' it is just creating a blank document named that, and I am stumped. Also any tips on best place to put a pipeline for only selecting the -Top 10 results once filtered down from the .wav files recently added??

$scriptPath = "/Users/robertunderwood/Splice/sounds/"
$Destination = "/Users/robertunderwood/NewSounds"
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.wav

    foreach($file in $fileNames){
        if ($file.LastWriteTime -ge (Get-Date).AddDays(-1)){   
            Write-Host $file.Name                                 
            Copy-Item $file -Destination $Destination
    }
 }
robertuxo
  • 35
  • 8

1 Answers1

2

Continuing from my comment...

You can always just create the folder and copy to it:

$scriptPath = "/Users/robertunderwood/Splice/sounds/"
$Destination = "/Users/robertunderwood/NewSounds"
Get-ChildItem -Path $scriptPath -Filter "*.wav" -Recurse | 
    Where-Object -FilterScript { $_.LastWriteTime -ge (Get-Date).AddDays(-1).Date } |
    Select-Object -First 10 | ForEach-Object -Begin {
        if (-not(Test-Path -Path $Destination -PathType Container)) {
            New-Item -Path $Destination -ItemType Container | Out-Null
        }
    } -Process {
        Copy-Item -Path $_.FullName -Destination $Destination
    }

Swapped your if statement to Where-Object to streamline the process. Also selected the top (first) 10 files found to copy.

You're expecting Copy-Item to create the folder and copy the files for you and that's where your issue occurs. Copy-Item can in fact create the folder first, then recursively copy to it when providing the -Recurse switch but, not when it's piped to it (... | Copy-Item); this includes even providing the -Force switch. So the alternative is to use the Foreach-Object cmdlet to create the folder first (in your Begin block), then copy to it. You can honestly create it whenever, wherever, using other methods, as long as it's not before the actual copying.

Abraham Zinala
  • 4,267
  • 3
  • 9
  • 24
  • 1
    I would do `(Get-Date).AddDays(-1).Date` to set the reference date to midnight. Otherwise, it depends on the time of day you run this code. – Theo Feb 06 '22 at 15:15
  • 1
    Sweet! Any chance you could explain what I was messing up in my code? It was only outputting blank documents when I would run it. – robertuxo Feb 06 '22 at 16:53
  • @robertuxo, see my edit for a better explanation. Also added Theo's suggestion. – Abraham Zinala Feb 06 '22 at 17:23