本文介绍了Filewatcher解压缩并在检测到事件(.zip)时进行处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个文件监视程序,并使用PowerShell执行以下流程:

I want to create a filewatcher and do the below flow using PowerShell:

监视文件夹A(.zip)中的文件→以(.zip)→的形式将文件移动到folderB.将移动的文件解压缩到文件夹C中(具有相同名称)→并触发批处理文件→对更多传入的.zip文件执行相同的操作.

Watch for file in folderA (.zip) → move the file to folderB as (.zip) → unzip the moved file in folderC (with same name) → and trigger a batch file → do the same for more incoming .zip files.

我检查了相关问题在StackOverflow中进行此操作,但我需要更多帮助.

I checked a related question to this in StackOverflow but I need some more help.

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

My PowerShell script is as below (I am using 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
    ...
}

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

You move the file to a different location, yet try to unzip it from the original location after it was already moved.

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

Change your scriptblock to something like this, and it should work as you expect:

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

这篇关于Filewatcher解压缩并在检测到事件(.zip)时进行处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:03