powershell 使用FilesystemWatcher将受监视的文件重命名为比其自身目录高一级的目录

xvw2m8pv  于 2022-11-10  发布在  Shell
关注(0)|答案(1)|浏览(136)

我有一个脚本,它将使用filesystemwatch来监视文件夹及其子目录中的新文件。一旦检测到新文件,它就会将该文件重命名为该文件所在的目录。
它工作得很好,但用法略有变化。不是将文件复制到受监视的子目录中,而是将包含该文件的文件夹放置到受监视的目录中。但是,如果检测到该文件,则会将该文件重命名为发送该文件的文件夹,而不是文件夹所在的目录。
示例:

monitored_directory
            monitored_subdirectory#1
                   new_folder       
                   new_file.txt

    new_file.txt becomes new_folder.txt

                instead of

    monitored_subdirectory#1.txt

以下是我目前掌握的信息:

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.IncludeSubdirectories = $true
$watcher.Path = 'C:\monitored_directory'
$watcher.EnableRaisingEvents = $true

$action =
{
    $path = $event.SourceEventArgs.FullPath
    $changetype = $event.SourceEventArgs.ChangeType
    $destination = 'C:\Detected\'

        Get-ChildItem C:\monitored_directory -Filter *.txt -Recurse | Copy-Item -Destination { "$($destination)$($_.Directory.Name+'.txt')" } 

}
Register-ObjectEvent $watcher 'Created' -Action $action

将文件夹放入“监控目录”文件夹中,会导致该文件以错误的文件夹命名。
任何帮助都将不胜感激。谢谢!

ffvjumwh

ffvjumwh1#

对于其他需要答案的人,只需将点符号从.Directory.Name更改为.Directory.Parent.Name

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.IncludeSubdirectories = $true
$watcher.Path = 'C:\monitored_directory'
$watcher.EnableRaisingEvents = $true

$action =
{
    $path = $event.SourceEventArgs.FullPath
    $changetype = $event.SourceEventArgs.ChangeType
    $destination = 'C:\Detected\'

    Get-ChildItem C:\monitored_directory -Filter *.txt -Recurse |
        Copy-Item -Destination { "$($destination)$($_.Directory.Parent.Name+'.txt')" } 
}
Register-ObjectEvent $watcher 'Created' -Action $action

相关问题