在远程PC上监视已更改文件的文件夹

时间:2018-03-23 11:10:17

标签: powershell scripting credentials

我的网络中的PC上有一个测量设备。 PC没有加入域,但有一个共享文件夹,我有一个用户名和密码。

我正在尝试构建一个Powershell脚本以从远程服务器监视此文件夹,对于新的CSV文件,该脚本会将该文件复制到指定的文件夹位置。我正在努力将参数传递给FileSystemWatcher cmdlet。

有什么想法吗?

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

编辑 - 该脚本将从加入我们域的服务器运行,因此需要将凭据传递到该文件夹​​,以便我可以访问它。我有这些证件。

1 个答案:

答案 0 :(得分:1)

我重构了一些代码(主要是因为我可以更容易理解它):

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

我在本地运行此代码并设法将$folder中创建的文件自动复制到$destination

FileSystemWatcher在当前用户的上下文中运行。在访问需要登录的远程系统的情况下,需要进行模拟。

如果远程系统只有本地用户,没有源系统可以登录的域用户,那么似乎不可能进行模拟。

有关假冒的详情,请参阅thisthis链接。