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

Filewatcher to unzip and process when event (.zip) is detected

我想创建一个文件观察器并使用 PowerShell 执行以下流程:

在文件夹 A 中寻找文件 (.zip) → 将文件作为 (.zip) 移动到文件夹 B → 将移动的文件解压缩到文件夹 C 中(同名)→ 并触发批处理文件 → 对更多传入文件执行相同操作.zip 文件。

我在 Whosebug 中检查了 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

这是你的错误:

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

    Unzip $path $outpath -Force
    ...
}

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

将您的脚本块更改为类似这样的内容,它应该会按预期工作:

$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
}