【问题标题】:Trigger script when new folder has been added to a location将新文件夹添加到某个位置时触发脚本
【发布时间】:2012-05-10 16:47:09
【问题描述】:

我正在自动化一个流程,并且已经为此制作了一个 powershell 脚本。现在我需要做一些事情,每次将新文件夹添加到特定位置(即删除新版本)时都会调用该脚本。 我应该为此使用什么。 WCF 太多了吗?如果没有,有任何线索吗?任何有用的链接。 还是另一个 powershell 脚本更好?

请记住,我也需要检查子文件夹。

谢谢。

【问题讨论】:

    标签: powershell automation


    【解决方案1】:

    我个人会使用 System.IO.FileSystemWatcher

    $folder = 'c:\myfoldertowatch'
    $filter = '*.*'                             
    $fsw = New-Object IO.FileSystemWatcher $folder, $filter 
    $fsw.IncludeSubdirectories = $true              
    $fsw.NotifyFilter = [IO.NotifyFilters]'DirectoryName' # just notify directory name events
    $onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {  ... do my stuff here } # and only when is created
    

    使用它来停止观看活动

    Unregister-Event -SourceIdentifier FileCreated
    

    【讨论】:

    • 但是这个脚本应该一直在运行,因为我不知道什么时候会删除新的构建。这种实现的安全性和稳定性如何?
    • 您可以使用 IO.FileSystemWatcher 类在 .net (vb/c#) 中创建一个应用程序(可能是 Windows 服务?)。就我个人而言,我在生产服务器上使用 powershell 脚本,从大约一年开始做同样的事情(不包括维护重启;))
    • 经过测试。工作 :D 非常感谢 Christian 和 Shay。我对此很陌生,这种帮助对我来说意义重大。
    【解决方案2】:

    试试这个:

    $fsw = New-Object System.IO.FileSystemWatcher -Property @{
        Path = "d:\temp"
        IncludeSubdirectories = $true #monitor subdirectories within the specified path
    }
    
    $event = Register-ObjectEvent -InputObject $fsw –EventName Created -SourceIdentifier fsw -Action {
    
        #test if the created object is a directory
        if(Test-Path -Path $EventArgs.FullPath -PathType Container)
        {
            Write-Host "New directory created: $($EventArgs.FullPath)"  
            # run your code/script here
        }
    }
    

    【讨论】:

    • 使用 [IO.NotifyFilters]'DirectoryName' 不需要测试是否是文件夹。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多