You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跨服务器文件夹监控及带凭据文件复制问题求助

解决远程文件夹监控+带凭据复制的PowerShell脚本问题

我来帮你捋捋这个脚本里的问题,主要是远程共享的凭据处理、路径格式,还有事件触发后的文件复制逻辑这几个地方出了问题,咱们一步步修正:

先说说原脚本的核心问题

  • 远程路径格式错误:你写的10.162.106.30\d$\IPE\CRMA\Por Tratar少了开头的双反斜杠,应该是标准的UNC路径\\10.162.106.30\d$\IPE\CRMA\Por Tratar,不然PowerShell识别不了远程共享。
  • FileSystemWatcher不直接支持传入凭据:远程共享的访问需要先建立带凭据的网络连接,不然会因为权限不足报错。
  • 事件处理里的逻辑不完整:你写的$nameFile.Subs...没写完,而且刚创建的文件可能还在被写入,直接复制会报错,得加个重试机制。
  • 多余的WMI查询:Get-WmiObject -Class Win32_Service这部分和文件夹监控没关系,完全可以删掉。

修改后的完整脚本

# 配置参数
$remoteServer = "10.162.106.30"
$watchFolder = "\\$remoteServer\d$\IPE\CRMA\Por Tratar"
$filter = '*.xls*'
$localDestFolder = 'D:\Import_Jbrandao\Click'
$remoteDestFolder = "\\$remoteServer\d$\IPE\CRMA\$(Get-Date -UFormat "%m-%Y")"

# 凭据配置
$userName = "UserName"
$password = "********"
$securePassword = $password | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($userName, $securePassword)

# 建立远程共享的凭据连接(避免权限问题)
try {
    # 检查是否已有连接,没有的话创建
    if (-not (Get-SmbMapping -RemotePath "\\$remoteServer\d$" -ErrorAction SilentlyContinue)) {
        New-SmbMapping -LocalPath "Z:" -RemotePath "\\$remoteServer\d$" -Credential $credential -ErrorAction Stop
        Write-Host "已建立远程共享连接 Z: -> \\$remoteServer\d$"
    }
}
catch {
    Write-Error "建立远程连接失败: $_"
    exit 1
}

# 确保目标文件夹存在
if (-not (Test-Path $remoteDestFolder)) {
    New-Item -Path $remoteDestFolder -ItemType Directory -Force | Out-Null
    Write-Host "已创建远程目标文件夹: $remoteDestFolder"
}
if (-not (Test-Path $localDestFolder)) {
    New-Item -Path $localDestFolder -ItemType Directory -Force | Out-Null
    Write-Host "已创建本地目标文件夹: $localDestFolder"
}

# 输出监控信息
Write-Host "--------------------------------------------------------"
Write-Host "监控文件夹: $watchFolder"
Write-Host "远程目标文件夹: $remoteDestFolder"
Write-Host "本地目标文件夹: $localDestFolder"
Write-Host "--------------------------------------------------------"

# 先注销已存在的同名事件(避免重复注册)
if (Get-EventSubscriber -SourceIdentifier FileCreated -ErrorAction SilentlyContinue) {
    Unregister-Event -SourceIdentifier FileCreated
    Write-Host "已注销旧的FileCreated事件订阅"
}

# 创建FileSystemWatcher
$fsw = New-Object IO.FileSystemWatcher $watchFolder, $filter -Property @{
    IncludeSubdirectories = $true
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}

# 注册文件创建事件
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $filePath = $Event.SourceEventArgs.FullPath
    $fileName = $Event.SourceEventArgs.Name
    $remoteDestPath = Join-Path $Event.MessageData.RemoteDest $fileName
    $localDestPath = Join-Path $Event.MessageData.LocalDest $fileName

    Write-Host "`n检测到新文件: $fileName"
    Write-Host "开始复制到远程目标: $remoteDestPath"
    Write-Host "开始复制到本地目标: $localDestPath"

    # 处理文件可能被占用的情况,重试3次
    $retryCount = 0
    $maxRetries = 3
    do {
        try {
            # 复制到远程目标
            Copy-Item -Path $filePath -Destination $remoteDestPath -Force -ErrorAction Stop
            # 复制到本地目标
            Copy-Item -Path $filePath -Destination $localDestPath -Force -ErrorAction Stop
            Write-Host "文件复制成功!"
            break
        }
        catch {
            $retryCount++
            Write-Warning "复制失败,正在重试第$retryCount次: $_"
            Start-Sleep -Seconds 2
        }
    } while ($retryCount -lt $maxRetries)

    if ($retryCount -eq $maxRetries) {
        Write-Error "重试$maxRetries次后仍无法复制文件: $fileName"
    }
} -MessageData @{
    RemoteDest = $remoteDestFolder
    LocalDest = $localDestFolder
}

Write-Host "** 已启动文件夹监控,按Ctrl+C停止 **"
# 保持脚本运行,等待事件触发
do {
    Start-Sleep -Seconds 1
} while ($true)

# 清理(脚本停止时执行)
finally {
    Unregister-Event -SourceIdentifier FileCreated
    Remove-SmbMapping -LocalPath "Z:" -Force -ErrorAction SilentlyContinue
    Write-Host "已清理事件订阅和远程共享连接"
}

关键修改点说明

  1. 修正远程路径格式:把所有远程路径改成标准UNC格式\\服务器名\共享名\路径,确保PowerShell能识别远程共享。
  2. 添加远程共享凭据连接:用New-SmbMapping建立带凭据的网络映射,这样FileSystemWatcher和Copy-Item都能通过这个映射获取权限访问远程文件夹。
  3. 完善事件处理逻辑:
    • 用$Event.SourceEventArgs.FullPath获取完整文件路径,避免只拿文件名导致的路径错误。
    • 添加了文件复制的重试机制,解决新创建的文件可能被占用无法复制的问题。
    • 通过-MessageData把目标文件夹路径传递到事件Action里,因为Action块无法直接访问外部变量。
  4. 添加文件夹存在性检查:自动创建不存在的目标文件夹,避免复制时报错。
  5. 事件订阅清理:启动前先注销同名事件,避免重复注册导致的冲突;脚本停止时清理事件和网络映射。

注意事项

  • 确保你的账号UserName有远程服务器d$共享的读写权限,以及目标文件夹的权限。
  • 如果不需要映射盘符,也可以用net use \\10.162.106.30\d$ /user:UserName Password来建立连接,效果是一样的。
  • 脚本运行时需要保持PowerShell窗口打开,或者把它做成Windows服务后台运行。

内容的提问来源于stack exchange,提问作者Joana Brandão

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:57:56