Powershell 脚本未触发

Powershell 脚本未触发

我对 powershell 还很陌生,但我在 PS ISE 中执行以下脚本:

$source = "E:\MEX_Websites\Customer_Hosting\MyFolderB\Reports\"
$filter = "*.*"

$fsw = New-Object System.IO.FileSystemWatcher $source, $filter -Property @{
IncludeSubDirectories=$false
NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite'
}

$onCreated = Register-ObjectEvent $fsw Changed -SourceIdentifier       MyFolderBReports -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"
Move-Item E:\MEX_Websites\Customer_Hosting\MyFolderB\Reports\*.* -Destination M:\MyFolderB\Reports\
}

因此,基本上它应该监听在 MyFolderB\Reports 文件夹中添加的文件,然后将其移至目标文件夹。一切看起来都很完美,我单击 PS ISE 中的“运行脚本”按钮,一切都完美执行,但什么也没发生。当我将文件放入基本文件夹时,它不会移动它。

知道我这里遗漏了什么步骤吗?

答案1

您仅订阅了 Changed 事件 - 当文件内容发生更改或被复制时会发生此事件。这不包括创建或移动的文件。

可能需要进行一些修改才能获得您想要的输出,但是以下方法应该有效:

$source = "C:\Ops"
$filter = "*.*"

$fsw = New-Object System.IO.FileSystemWatcher $source, $filter -Property @{
    IncludeSubDirectories=$false
    NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite'
}

$onCreated = @()

@(
    "Changed",
    "Created",
    "Renamed"
) | Foreach-Object {
    $onCreated += Register-ObjectEvent $fsw -EventName $_ -SourceIdentifier "MyFolderBReports_$_" -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"
        Move-Item C:\Ops\*.* -Destination C:\Ops\Test
    }
}

除了 Changed 事件外,这还会注册 Created 和 Renamed 事件,因此应该涵盖所有基础。查看$fsw | GM显示还有和事件Deleted,但对于您的目的,我认为它们不是必需的。DisposedError

相关内容