Below is my file moving script. My problems:
- Super slow in moving files
- It doesnt move existing files and
- Once it moves it also logs it x5, like its moved the same file x5
- Filewatcher kinda not working as it doesnt recognize new files, have to rerun the script a few times for it to make the move
# Define variables
$LogFilePath = "C:\Logs\FileTransferLog.txt"
$ServiceAccountUserName = "test\test"
$ServiceAccountPassword = ConvertTo-SecureString "Test123" -AsPlainText -Force
$ServiceAccountCredential = New-Object System.Management.Automation.PSCredential($ServiceAccountUserName, $ServiceAccountPassword)
# Define the array of users
$Users = @("TEST")
foreach ($User in $Users) {
$SourceShare1 = "\\TEST\TEST\$User\"
$DestinationShare1 = "\\TEST1\TEST\$User\"
$WatcherServer1 = New-Object System.IO.FileSystemWatcher
$WatcherServer1.Path = $SourceShare1
$WatcherServer1.Filter = "*.*"
$WatcherServer1.IncludeSubdirectories = $false
$WatcherServer1.EnableRaisingEvents = $true
# Define the event handler for new file creation
$OnCreated = Register-ObjectEvent $WatcherServer1 "Created" -Action {
# Get the name of the new file
$NewFile = $Event.SourceEventArgs.Name
# Move the new file to the archive share using service account
Move-Item "$SourceShare1\$NewFile" $DestinationShare1
# Log the file transfer activity to a text file
Write-Output "Moved file $NewFile from $SourceShare1 to $DestinationShare1 at $(Get-Date)" | Out-File $LogFilePath -Append
}
}
# Wait for events to occur
while ($true) { Start-Sleep -Seconds 1 }