文件组织powershell脚本

时间:2013-04-27 01:45:32

标签: file powershell filesystemwatcher organization

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

以下是我到目前为止所写的内容:请记住,我是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
}
}
}
}

由于某种原因,它不会移动文件。我已经看到了变化,但没有移动文件。

请帮助!

1 个答案:

答案 0 :(得分: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