Reputation: 13
I am working on a PowerShell script for PowerShell v3 on a Server 2012 R2 system to recursively search the specified folders in the source path and copy wav files less than 5 minutes old to a destination directory.
In this sample code I would need \\source\path\folder1 and \\source\path\folder2 to be searched for wav files and then have them copied into the root destination directory \\destination\path
I was attempting to setup a scheduled task to run this every 5 minutes thus the reason for trying to use {$_.LastWriteTime -gt (Get-Date).AddMinutes(-5)}
without success. Any other suggestions on how to prevent duplicate copies would be great.
I then would like the script to append to a log file of files copied for future reference with a log filed named the current date.
Any suggestions would be greatly appreciated.
$Dst = '\\destination\path'
$Src = '\\source\path'
$LogFolder = "\\log\path"
$FolderName = "folder1","folder2"
$FileType = '*.wav'
Get-ChildItem -Path $Src -Filter $FolderName -Recurse -Force |
Where-Object {$_.PSIsContainer} |
Where-Object {$_.LastWriteTime -gt (Get-Date).AddMinutes(-5)} |
ForEach-Object {
Copy-Item -Path (Join-Path -Path $_.FullName -ChildPath '\*') -Filter $FileType -Destination $Dst -Force | Out-File $LogFolder $(get-date -f MM-dd-YYYY) + .log
}
Upvotes: 1
Views: 1687
Reputation: 622
As FoxDeploy mentioned and a short test confirmed, this isn't the problem:
{$_.LastWriteTime -gt (Get-Date).AddMinutes(-5)}
I advise you to better use multiple paths instead of filtering the folder names, so that you can try the follwing to get your waves:
Get-ChildItem -Path $paths -Filter "*.wav" -File -Recurse -Force
And im a bit wondering why $Src = '\source\path' doesn't start with a dot. In my case, all trials to get along without failed.
I guess you want to append context to your log file, so add: -noclubber -append to Outfile.
Upvotes: 0
Reputation: 13537
The reason this code isn't doing anything is that you're filtering on the second line, here:
Where-Object {$_.PSIsContainer}
You're filtering just for directories, not only for files. Since you don't later in the code recurse through the folders, that's why nothing is happening.
I would remove that statement, and specify -Include *.wav
on your initial Get-ChildItem
cmd.
Upvotes: 0
Reputation: 1972
You can add a test-path check before copying to prevent grabbing the same file twice. Would CreationTime be a better check than LastWriteTime?
$Dst = '\\destination\path'
$Src = '\\source\path'
$LogFolder = "\\log\path"
$FolderName = "folder1","folder2"
$FileType = '*.wav'
Get-ChildItem -Path $Src -Filter $FolderName -Recurse -Force |
Where-Object {$_.PSIsContainer} |
Where-Object {$_.LastWriteTime -gt (Get-Date).AddMinutes(-5)} |
ForEach-Object {
if (Test-Path "$Dst\$_.FullName" -eq 0)
{
Copy-Item -Path (Join-Path -Path $_.FullName -ChildPath '\*') -Filter $FileType -Destination $Dst -Force | Out-File $LogFolder $(get-date -f MM-dd-YYYY) + .log
}
}
Upvotes: 1