gpt4 book ai didi

powershell - 使用System.IO.FileSystemWatcher后使用Powershell循环浏览文件

转载 作者:行者123 更新时间:2023-12-02 23:11:21 25 4
gpt4 key购买 nike

在PowerShell脚本中需要一些帮助,该脚本监视文件夹以创建具有.csv扩展名的新文件。
检测到创建新文件后,将执行以下操作…

  • 文件的详细信息发送到日志文件
  • 该文件的副本将发送到另一个名为“1_ToBeProcessed \ MyImport.csv”的文件夹(请注意,该文件已重命名为MyImport.csv)。
  • 该文件被移动到目录“\ MYSERVER \ MYCOMPANY \ MYFOLDER \ MyHistory”(及其原始文件名)
  • 调用一个表达式以运行.bat文件,该文件将获取位于“\ MYSERVER \ MYCOMPANY \ MYFOLDER \ 1_ToBeProcessed”中的文件,并将该文件导入应用程序。
  • 然后,脚本休眠60秒,以允许导入完成,然后再处理下一个文件。
    除非在脚本运行时创建另一个文件,否则此脚本都可以很好地工作。
    相同类型的多个文件可能会同时进入监视文件夹。因此,该脚本可能会遍历五个文件,然后另一个文件会进入目录。发生这种情况时,脚本似乎会重新开始并开始遍历文件……但它会不断地反复遍历相同的文件。
    我希望有人可以为我指出此脚本做错的正确方向。在添加新文件之前,如何在重新启动之前完成当前循环中正在处理的文件?
    可以提供的任何帮助将不胜感激!

  • 这就是我目前拥有的...
    #Define watcher; Set path to watch; Set filter on file type
    $filewatcher = New-Object System.IO.FileSystemWatcher
    $filewatcher.Path = "\\MYSERVER\MYCOMPANY\MYFOLDER"
    $filewatcher.Filter = "*.csv"

    #Define "move to" and "copy to" paths
    $moveTo = "\\MYSERVER\MYCOMPANY\MYFOLDER\MyHistory"
    $copyTo = "\\MYSERVER\MYCOMPANY\MYFOLDER\1_ToBeProcessed\MyImport.csv"


    #Define actions after an Event is Detected
    $action = {$files = Get-ChildItem -Path $filewatcher.Path -Filter filewatcher.Filter
    foreach ($file in $files)
    {
    #Define variables for log file
    $changeType = $Event.SourceEventArgs.ChangeType
    $logline = "$(Get-Date), $changeType, $file"
    #Actions to take
    Add-Content "\\MYSERVER\MYCOMPANY\MYFOLDER\3_Log\MyImportLog.txt" -value $logline
    Copy-Item $file.FullName -Destination $copyTo
    Move-Item $file.FullName -Destination $moveTo -Force
    Invoke-Expression "& '\\MYSERVER\MYCOMPANY\MYFOLDER\4_Scripts\PSscriptToRunBATfile.ps1'"
    #Pause the script for 60 seconds to allow it to finish posting the import before going to the next record
    Start-Sleep -Seconds 60
    }
    }

    #Decide which events should be watched and set check frequency
    $onCreated = Register-ObjectEvent -InputObject $filewatcher -EventName "Created" -SourceIdentifier FileCreated -Action $action

    最佳答案

    我建议不要循环,而是在创建/更改文件时对其进行处理。也许如果您有很多文件要开始,则可以:

    (a)首先循环(并且仅循环一次)。然后,使文件监视程序可以对之后发生过更改的文件采取行动。

    (b)使用FileChanged和FileCreated启用文件监视程序,然后“触摸”所有文件以启动代码。

    # based on the script by By BigTeddy 05 September 2011
    # simplified by Andy Myatt, to use one script block
    # https://gallery.technet.microsoft.com/scriptcenter/Powershell-FileSystemWatche-dfd7084b

    param(
    [string]$folderToWatch = "D:\Temp"
    , [string]$filter = "*.*"
    , [string]$logFile = "D:\Temp\Temp2\filewatcher.log"
    )

    # In the following line, you can change 'IncludeSubdirectories to $true if required.
    $fsw = New-Object IO.FileSystemWatcher $folderToWatch, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

    # This script block is used/called by all 3 events and:
    # appends the event to a log file, as well as reporting the event back to the console
    $scriptBlock = {

    # REPLACE THIS SECTION WITH YOUR PROCESSING CODE
    $logFile = $event.MessageData # message data is how we pass in an argument to the event script block
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "$timeStamp|$changeType|'$name'" -fore green
    Out-File -FilePath $logFile -Append -InputObject "$timeStamp|$changeType|'$name'"
    # REPLACE THIS SECTION WITH YOUR PROCESSING CODE

    }

    # Here, all three events are registered. You need only subscribe to events that you need:
    Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -MessageData $logFile -Action $scriptBlock
    Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -MessageData $logFile -Action $scriptBlock
    Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -MessageData $logFile -Action $scriptBlock

    # To stop the monitoring, run the following commands:
    # Unregister-Event FileDeleted ; Unregister-Event FileCreated ; Unregister-Event FileChanged


    #This script uses the .NET FileSystemWatcher class to monitor file events in folder(s).
    #The advantage of this method over using WMI eventing is that this can monitor sub-folders.
    #The -Action parameter can contain any valid Powershell commands.
    #The script can be set to a wildcard filter, and IncludeSubdirectories can be changed to $true.
    #You need not subscribe to all three types of event. All three are shown for example.

    关于powershell - 使用System.IO.FileSystemWatcher后使用Powershell循环浏览文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39393645/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com