1

I'm pretty new to powershell but im executing the following script in 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\
}

So basically it should listen for a file to be added in the MyFolderB\Reports Folder then move it over to the Destination folder. It all looks perfect and i click the "Run Script" button in PS ISE and it all executes perfectly but nothing happens. When i put a file in the base folder it doesnt move it.

Any ideas what step im missing here?

0

You've only subscribed to the Changed event - this occurs when the content of a file is changed, or it is copied. This does not include files that are created or moved.

May want to tinker to get the output how you want it, but the following should work:

$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
    }
}

This is registering to the Created and Renamed events in addition to the Changed event, so should cover all your bases. Looking at $fsw | GM shows there is additionally Deleted, Disposed and Error events but for your purpose I don't think they are required.

  • Just a note, if you are trying to right click > new file it will move it before you get a chance to name it – Deadly-Bagel Jul 1 '16 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.