且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

文件组织PowerShell脚本

更新时间:2022-12-06 08:35:15

事件的Action脚本块运行

尝试移动这一行:

  $ PickupDirectory = Get-ChildItem -recurse -PathC:\ users \Dave\desktop\test

放入您的动作脚本块,看看是否有帮助。



如果一个Switch的语句,但这只是个人喜好。

添加该父路径的一种方法



[void] [IO.Directory] ​​:: CreateDirectory(c:\音乐\\ $ $父母)
move-Item $ file.FullName -destination c:\music\ $ parent


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!

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