自动检测文件,而不使用任务计划程序

时间:2019-06-04 09:46:46

标签: powershell

我有这段代码,它从d2ve38282拾取文件并将其本地拖放到:D:\ Test \ MEP \ TST \ input \ tEST。

第一次尝试:

Move-Item "\\d2ve38282\AS2\Inbound\Test Orders\*.txt" -Destination "D:\Test\MEP\TST\input\tEST"

第二次尝试:

$FTBM = 'D:\Test Folder'
$FLTR = '*.*'

$watcher = New-Object IO.FileSystemWatcher $FTBM, $FLTR -Property @{
    IncludeSubDirectories = $false;
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}

Move-Item "D:\Test Folder\*.txt" -Destination "D:\Test Folder 2"

Register-ObjectEvent $watcher Created -SourceIdentifier FileCreated -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
}
#Unregister-Event FileCreated

第三次尝试:

$FTBM = 'D:\Test Folder'
$FLTR = '*.*'

$watcher = New-Object IO.FileSystemWatcher $FTBM, $FLTR -Property @{
    IncludeSubDirectories = $false;
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}

Register-ObjectEvent $watcher Created -SourceIdentifier FileCreated -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    Move-Item "D:\Test Folder\*.txt" -Destination "D:\Test Folder 2"
}"
#Unregister-Event FileCreated

如何设置它在以下文件夹中找到测试订单时自动运行:D:\ Test文件夹\?

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

$folder = 'c:\scripts\test' # Enter the root path you want to monitor.
$filter = '*.*'  # You can enter a wildcard filter here.

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

# Here, all three events are registerd.  You need only subscribe to events that you need:

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}

Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore red
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}

Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore white
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}

来源:FileSystemWatcher

Dot Net版本总是比WMI更好。希望对您有所帮助。