0

我试图监视一个目录及其子目录中的新文件。我想查看文件扩展名并根据文件扩展名将其移动到相应的文件夹中。例如,如果我有一个文件夹“C:\users\dave\desktop\test”,并且我将一个 avi 文件下载到该文件夹​​中,则需要像脚本一样查看它并自动将文件移动到 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
}
}
}
}

由于某种原因,它不会移动文件。我已经得到它来查看更改,但不移动文件。

请帮忙!

4

1 回答 1

0

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
于 2013-04-27T15:43:04.877 回答