Filewatcher在检测到事件(.zip)时进行解压缩和处理

时间:2017-03-13 08:53:09

标签: powershell powershell-v3.0 filesystemwatcher

我想创建一个filewatcher并使用PowerShell执行以下操作:

在folderA(.zip)中查看文件→将文件移动到folderB为(.zip)→将文件夹中的已移动文件解压缩(同名)→然后触发批处理文件→对更多传入执行相同操作.zip文件。

我在StackOverflow中检查了related question,但我还需要一些帮助。

我的PowerShell脚本如下(我使用的是PowerShell ISE):

while ($true) {
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "D:\LocalData\Desktop\folderA"
    $watcher.Filter = "*.zip*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true
    $tempfolder = "D:\LocalData\Desktop\folderA\folderB"
    $outpath = "D:\LocalData\Desktop\folderA\folderB\folderC"

    #Function to Unzip the moved item
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    function Unzip {
        Param([string]$path, [string]$outpath)
        [System.IO.Compression.ZipFile]::ExtractToDirectory($path, $outpath)
    }

    $action = {
        $path = $Event.SourceEventArgs.FullPath
        $changeType = $Event.SourceEventArgs.ChangeType
        $name = $Event.SourceEventArgs.Name
        Move-Item $path $tempfolder

        Unzip $path $outpath -Force # this line is not being read, it goes to the function block, and slips down to the action block

        $logline = "$(Get-Date), $changeType, $path" # no log is generated
        Add-Content -Path "d:\LocalData\folderA\Watcherlog.log" $logline
        Start-Process -Path "d:\LocalData\process.bat"
    }
    Register-ObjectEvent $watcher "Created" -Action $action
    Start-Sleep 2
}
Unregister-Event -SourceIdentifier FileCreated

1 个答案:

答案 0 :(得分:1)

你的错误是:

$action = {
    ...
    Move-Item $path $tempfolder

    Unzip $path $outpath -Force
    ...
}

您将文件移动到其他位置,但在已移动后,尝试将其从原始位置解压缩。

将您的scriptblock更改为类似的内容,它应该按预期工作:

$action = {
    $path = $Event.SourceEventArgs.FullPath
    $changeType = $Event.SourceEventArgs.ChangeType

    Unzip $path $outpath -Force
    Remove-Item $path

    "$(Get-Date), $changeType, $path" | Add-Content -Path "d:\LocalData\folderA\Watcherlog.log"
    Start-Process -FilePath "d:\LocalData\process.bat" -Wait
}