Monitor folder on remote PC for changed files

感情迁移 提交于 2019-12-25 01:45:52

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/49448361/monitor-folder-on-remote-pc-for-changed-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!