Reputation: 35
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
}
}
Upvotes: 2
Views: 330
Reputation: 4694
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.
Upvotes: 2