注意:运行 PowerShell v3
我目前的目录设置是:
\ftproot\001\converted
\ftproot\001\inbound
\ftproot\001\pdf
\ftproot\002\converted
\ftproot\002\inbound
\ftproot\002\pdf
\ftproot\xxx\converted
\ftproot\xxx\inbound
\ftproot\xxx\pdf
每个 FTP 用户都映射到一个入站目录。如果结构可以使解决方案更容易,则可以更改
\ftproot\converted\001
\ftproot\converted\002
\ftproot\converted\xxx
\ftproot\inbound\001
\ftproot\inbound\002
\ftproot\inbound\xxx
\ftproot\pdf\001
\ftproot\pdf\002
\ftproot\pdf\xxx
我需要监视每个入站目录中的 TIFF 文件,并在添加新的 FTP 用户和入站目录时拾取它们(遵循相同的结构),因此我不希望为每个新用户修改脚本。
目前的脚本是这样的:
$fileDirectory = "\ftproot";
$folderMatchString = "^[0-9]{3}$";
$inboundDirectory = "inbound";
$filter = "*.tif";
$directories = dir -Directory $fileDirectory | Where-Object {$_.Name -match $folderMatchString}
foreach ($directory in $directories) {
$sourcePath = "$fileDirectory\$directory\$inboundDirectory"
if(Test-Path -Path $sourcePath -pathType container ) {
// Problem is here //
$fsw = New-Object IO.FileSystemWatcher $sourcePath, $filter -Property @{
IncludeSubdirectories = $false
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
}
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp"
}
我将 New-Object IO.FileSystemWatcher 包装在一个循环中,因此在上面的示例中,只会监视最后一个目录。
是否可以创建一个数组或列表或类似的 IO.FileSystemWatcher?如果是这样,我如何为每个实例编写 Register-ObjectEvent 代码?最终将有一百多个目录需要监控(并且正在缓慢增加),但相同的操作适用于所有入站文件夹。
或者我应该研究更好的解决方案?
每个 FTP 用户的过程都是相同的,文件需要位于可以链接回用户的目录中。将监视入站目录中是否有上传的 TIFF 文件,当检测到文件时,多页 TIFF 将被拆分为单独的文件并移动到转换后的目录中,当在转换中检测到新文件时,将对 TIFF 文件执行另一个操作,然后它被转换为 PDF 并移动到 PDF 文件夹。
谢谢
Solution
$result = @($directoriesOfInterest | ? { Test-Path -Path $_ } | % {
$dir = $_;
$fsw = New-Object IO.FileSystemWatcher $dir, $filter -Property @{
IncludeSubdirectories = $false
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
};
$oc = Register-ObjectEvent $fsw Created -Action {
$path = $Event.SourceEventArgs.FullPath;
$name = $Event.SourceEventArgs.Name;
$changeType = $Event.SourceEventArgs.ChangeType;
$timeStamp = $Event.TimeGenerated;
Write-Host "The file '$name' was $changeType at $timeStamp";
};
new-object PSObject -Property @{ Watcher = $fsw; OnCreated = $oc };
});