这个 PowerShell 脚本可以用于在不同网络位置的两个文件夹之间进行文件同步。它会监视源文件夹的变化,并将变化同步到目标文件夹中。以下是完整的脚本:
$sourceFolder = "\\192.168.0.146\c$\ViewSystem\ROLLS\FN2"
$targetFolder = "\\192.168.0.182\fn22\FN2\demo"
$syncWatcher = New-Object System.IO.FileSystemWatcher
$syncWatcher.Path = $sourceFolder
$syncWatcher.IncludeSubdirectories = $true
$syncWatcher.EnableRaisingEvents = $true
$syncAction = {
$changedItem = $eventArgs.FullPath
$relativePath = $changedItem -replace [regex]::Escape($sourceFolder), ''
$targetItem = Join-Path -Path $targetFolder -ChildPath $relativePath
if (Test-Path -Path $changedItem -PathType Leaf) {
# 文件被创建或修改
if (Test-Path -Path $targetItem -PathType Leaf) {
$sourceSize = (Get-Item $changedItem).Length
$targetSize = (Get-Item $targetItem).Length
if ($sourceSize -ne $targetSize) {
Copy-Item -Path $changedItem -Destination $targetItem -Force
Write-Host "已同步变动文件: $relativePath"
}
} else {
Copy-Item -Path $changedItem -Destination $targetItem -Force
Write-Host "已同步新文件: $relativePath"
}
} elseif (Test-Path -Path $changedItem -PathType Container) {
# 文件夹被创建
if (-not (Test-Path -Path $targetItem -PathType Container)) {
New-Item -Path $targetItem -ItemType Directory -Force
Write-Host "文件夹已创建: $relativePath"
}
} elseif (-not (Test-Path -Path $changedItem)) {
# 文件或文件夹被删除
if (Test-Path -Path $targetItem) {
Remove-Item -Path $targetItem -Force -Recurse
Write-Host "已删除: $relativePath"
}
}
}
Register-ObjectEvent -InputObject $syncWatcher -EventName "Created" -Action $syncAction
Register-ObjectEvent -InputObject $syncWatcher -EventName "Changed" -Action $syncAction
Register-ObjectEvent -InputObject $syncWatcher -EventName "Deleted" -Action $syncAction
# 循环遍历整个文件夹并复制文件
Get-ChildItem -Path $sourceFolder -File -Recurse | ForEach-Object {
$relativePath = $_.FullName -replace [regex]::Escape($sourceFolder), ''
$targetItem = Join-Path -Path $targetFolder -ChildPath $relativePath
Copy-Item -Path $_.FullName -Destination $targetItem -Force
Write-Host "已复制文件: $relativePath"
}
Write-Host "正在监视和同步…"
try {
do {
Wait-Event -Timeout 60
} while ($true)
} finally {
Unregister-Event -SourceIdentifier $syncWatcher.Created
Unregister-Event -SourceIdentifier $syncWatcher.Changed
Unregister-Event -SourceIdentifier $syncWatcher.Deleted
$syncWatcher.Dispose()
}
要使用这个脚本,请按照以下步骤进行操作:
- 将
$sourceFolder和$targetFolder分别替换为源文件夹和目标文件夹的实际路径。 - 将脚本保存为
.ps1文件(例如FileSync.ps1)。 - 在 PowerShell 窗口中运行脚本:
.\FileSync.ps1。
要在每次开机时自动运行这个 PowerShell 脚本,你可以将脚本的执行添加到计算机的启动项中。这样,每次计算机启动时,脚本都会自动运行。
1. 打开 PowerShell 窗口(以管理员身份运行)。
2. 输入以下命令来打开计划任务管理器:
schtasks /create /tn "FileSync" /tr "powershell.exe -File 'C:\Users\xiaosun.GLOTECH-GF\Desktop\FileSync.ps1'" /sc onlogon /ru USERNAME /rl HIGHEST
"FileSync":任务的名称,你可以根据需要进行更改。"C:\Users\xiaosun.GLOTECH-GF\Desktop\FileSync.ps1":脚本的实际路径。请将其替换为你的脚本的路径。USERNAME:你的计算机用户名。请将其替换为你的实际用户名。
3. 运行以上命令后,计划任务将会被创建,它将在每次用户登录时运行指定的 PowerShell 脚本。
请确保将脚本的路径和用户名替换为你的实际值。完成后,每次计算机启动时,该脚本都会自动运行并开始监视和同步文件夹。