使用powershell监控某个路径下是否有新的文件生成,如果有新的文件生成则拷贝:

代码如下:

#script for monitor and copy file

$global:folder = '\\Share\lbx'                # upload path 
$filter = '*.*'                             #copy file type
$global:path

Function MonitorAndCopyFile{

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
  IncludeSubdirectories = $true              # set this according to your requirements
  NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$global:path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
$Time = (get-date)-$timeStamp
while($Time.TotalSeconds -le 120){
  Start-sleep -s (120-$Time.TotalSeconds)
  $Time = (get-date)-$timeStamp
} 
  $rootpath = $global:path | split-path -parent 
  $ac=($rootpath -split '\\')[4..(($rootpath -split '\\').count -1)] -join '\'
  $global:destination = 'c:\'  # destination path
  $global:destination=$global:destination+$ac
  Write-Host $global:destination
  if(!(Test-Path "$global:destination")){
          New-Item  $global:destination -type directory
  }
  copy-Item -Path $global:path -Destination $global:destination -Recurse -Force # Force will overwrite files with same name
  }
}

MonitorAndCopyFile

  

posted on 2013-07-04 15:18  一个土著  阅读(164)  评论(0)    收藏  举报