AdzzzUK
AdzzzUK

Reputation: 298

Monitor folder on remote PC for changed files

I have a measuring device on a PC in our network. The PC is not joined to the domain, however has a shared folder for which I have a username and password.

I am attempting to build a Powershell script to monitor this folder from a remote server, for new CSV files, the script will then copy the file to a specified folder location. I am struggling to pass through the parameters to the FileSystemWatcher cmdlet.

Any ideas?

$folder = '\\remoteip\folder\subfolder'# <--'<full path to the folder to watch>'
$filter = '*.csv'
$destination = '\\mynetworkstorage\folder\' # <--' Where is the file going?

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
    IncludeSubdirectories = $true              # <-- set this according to your requirements
    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"
    Copy-Item $path -Destination $destination -Force -Verbose
}

EDIT - The script will be run from a server joined to our domain, so there is a need to pass through credentials to the folder in order that I can access it. I have these credentials.

Upvotes: 1

Views: 1239

Answers (1)

kim
kim

Reputation: 3421

I refactored the code a little (mainly so I could more easily understand it):

$folder = '\\localhost\c$\tmp'
$filter = '*.*'
$destination = '\\localhost\c$\tmp_destination\' 

$fsw = New-Object IO.FileSystemWatcher
$fsw.Path = $folder
$fsw.Filter = $filter
$fsw.IncludeSubdirectories = $true
$fsw.EnableRaisingEvents = $true  
$fsw.NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'

$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"
    Copy-Item $path -Destination $destination -Force -Verbose    
}  

$created = Register-ObjectEvent $fsw Created -Action $action

while ($true) {sleep 1}

I ran this code locally and managed to get files created in $folder automatically copied to $destination.

FileSystemWatcher run in the context of the current user. In the case of accessing remote systems that require login, impersonation is required.

If the remote system only got local users, no domain user that the source system can log on as, then impersonation does not seem to be possible.

See this and this link for more details on impersonation.

Upvotes: 1

Related Questions