2013-04-27 111 views
0

我试图监视一个目录及其新文件的子目录。我想查看文件扩展名,并根据文件扩展名将其移至相应的文件夹。例如,如果我有一个文件夹“C:\ users \ dave \ desktop \ test”,并且我下载了一个avi文件到该文件夹​​,就像脚本一样查看它并自动将文件移动到C:\ movies。或者,如果我下载一个完整的mp3文件文件夹,我希望它自动将整个文件夹移动到C:\ music。现在它只将mp3文件移动到C:\ music中,但我无法弄清楚如何移动父文件夹。文件组织PowerShell脚本

以下是我迄今写过的内容:请记住,我是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 
} 
} 
} 
} 

出于某种原因,它不移动文件。我得到它看到的变化,但不移动文件。

请帮忙!

+0

退房这个程序 - [DropIt(http://dropit.sourceforge.net)做这个。 – 2013-04-27 11:58:41

+0

谢谢安迪,但是,我必须创建这个作业。我的编程知识已经让我走了这么远,但是我缺乏脚本知识却使我停下脚步。 – OOoNiMrOdoOO 2013-04-27 13:43:21

回答

0

事件的Action脚本块在不同的运行空间中运行,并且主脚本中的变量在此处不可见。

尝试移动这一行:

$PickupDirectory = Get-ChildItem -recurse -Path "C:\users\Dave\desktop\test" 

到动作脚本块,看看有没有什么帮助。

我还想交换一堆Switch的If语句,但这只是个人喜好。

的一种方式补充说,父路径

$parent = ($file.fullname).split('\')[-2] 
[void][IO.Directory]::CreateDirectory("c:\music\$parent") 
move-Item $file.FullName -destination c:\music\$parent 
+0

太棒了!感谢mjolinor!任何想法如何让父目录随它移动?所以我没有一个混合的MP3文件一堆文件夹? – OOoNiMrOdoOO 2013-04-27 16:01:20

+0

已更新的答案。 – mjolinor 2013-04-27 16:26:22

+0

嗯,我刚刚结束了一个以父文件夹命名的黑色文件。它使用文件夹名称而不是文件夹创建了一个文件。 – OOoNiMrOdoOO 2013-04-27 16:47:21