问题
Im trying to monitor a directory and its subdirectory for new files. I want to look at the file extension and move it to its appropriate folder based on the file extension. For example, If i have a folder "C:\users\dave\desktop\test" and i download an avi file to that folder, id like the script to see it and move the file to a C:\movies automatically. Or if i download an entire folder of mp3 files, i'd like it to move that entire folder to C:\music automatically. Right now it moves just the mp3 files into C:\music, but I cant figure out how to move the parent folder too.
Here is what i have written so far: Keep in mind, I'm new to powershell!
if (!(Test-Path -path C:\music))
{
New-Item C:\music\ -type directory
}
if (!(Test-Path -path C:\movies))
{
New-Item C:\movies\ -type directory
}
$PickupDirectory = Get-ChildItem -recurse -Path "C:\users\Dave\desktop\test"
$folder = 'C:\users\Dave\desktop\test'
$watcher = New-Object System.IO.FileSystemWatcher $folder
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
$watcher
Register-ObjectEvent $watcher -EventName Changed -SourceIdentifier 'Watcher' -Action {
foreach ($file in $PickupDirectory)
{
if ($file.Extension.Equals('.avi'))
{
Write-Host $file.FullName #Output file fullname to screen
Write-Host $Destination #Output Full Destination path to screen
move-Item $file.FullName -destination c:\movies
}
if ($file.Extension.Equals('.mp3'))
{
Write-Host $file.FullName #Output file fullname to screen
Write-Host $Destination #Output Full Destination path to screen
move-Item $file.FullName -destination c:\music
}
if ($file.Extension.Equals(".mp4"))
{
Write-Host $file.FullName #Output file fullname to screen
Write-Host $Destination #Output Full Destination path to screen
move-Item $file.FullName -destination c:\movies
}
}
}
}
For some reason, it does not move the files. Ive gotten it to see changes, but not move files.
Please Help!
回答1:
The Action scripblock of events runs in a different runspace, and the variables in your main script aren't visible there.
Try moving this line:
$PickupDirectory = Get-ChildItem -recurse -Path "C:\users\Dave\desktop\test"
into your action script block and see if that helps.
I'd also trade that stack of If statements for a Switch, but that's just personal preference.
One way to add that parent path
$parent = ($file.fullname).split('\')[-2]
[void][IO.Directory]::CreateDirectory("c:\music\$parent")
move-Item $file.FullName -destination c:\music\$parent
来源:https://stackoverflow.com/questions/16247469/file-organization-powershell-script