【问题标题】:File organization powershell script文件组织PowerShell脚本
【发布时间】:2013-04-27 01:45:32
【问题描述】:

我正在尝试监视一个目录及其子目录中的新文件。我想查看文件扩展名并根据文件扩展名将其移动到相应的文件夹中。例如,如果我有一个文件夹“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
}
}
}
}

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

请帮忙!

【问题讨论】:

  • 看看这个应用程序 -- DropIt 这样做。
  • 谢谢安迪,但是,我必须为作业创建这个。我的编程知识让我走到了这一步,但是我缺乏脚本知识让我停了下来。

标签: file powershell filesystemwatcher organization


【解决方案1】:

事件的动作脚本块在不同的运行空间中运行,主脚本中的变量在那里不可见。

尝试移动这条线:

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

进入你的动作脚本块,看看是否有帮助。

我也会用那堆 If 语句换一个 Switch,但这只是个人喜好。

添加父路径的一种方法

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

【讨论】:

  • 太棒了!谢谢mjolinor!知道如何让父目录随之移动吗?所以我没有包含一堆混合 mp3 文件的文件夹?
  • 嗯,我刚刚得到了一个以父文件夹命名的黑色文件。它使用文件夹名称创建了一个文件,而不是文件夹。
  • 这听起来可能是您的 Get-Childitem 没有过滤掉目录的结果。
  • 代码有问题吗:$PickupDirectory = Get-ChildItem -recurse -Path "C:\users\Dave\desktop\test" ?
  • 实际上,我认为这是因为如果目标目录尚不存在,move-item 不会自动创建目标目录,因此您必须在移动之前执行此操作。更新了代码。
猜你喜欢
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
  • 1970-01-01
  • 2020-11-02
相关资源
最近更新 更多