Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Script to copy new Files and create Folder

Status
Not open for further replies.

sugram

Technical User
Feb 5, 2021
26
DE
Hello

I would like if there is a new file in a directory or subdirectory that File copied and the folders are created at the destination if they do not exist.

My actual Code is:
Code:
$Quellverzeichnis = "\\Server1\xxx\yyy\zzz"
$Zielverzeichnis = "\\Server2\aaa\bbb\ccc"

$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path = $Quellverzeichnis
$FileSystemWatcher.Filter = "*.*"
$FileSystemWatcher.IncludeSubdirectories = $true
$FileSystemWatcher.EnableRaisingEvents = $true

$OnCreated = Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action {
    $NeueDatei = $Event.SourceEventArgs.FullPath
    $ZielDatei = Join-Path $Zielverzeichnis (Get-Item $NeueDatei).FullName.Substring($Quellverzeichnis.Length + 1)

    $ZielVerzeichnisExistiert = Test-Path $ZielDatei -PathType Container
    if (-not $ZielVerzeichnisExistiert) {
        New-Item -Path $ZielDatei -ItemType Directory -Force
    }

    
    Copy-Item -Path $NeueDatei -Destination $ZielDatei -Force

    Write-Host "Datei kopiert: $NeueDatei -> $ZielDatei"
}

Write-Host "Überwachung gestartet. Drücke 'Ctrl+C' zum Beenden."

try {
    while ($true) {
        Wait-Event -Timeout 1
    }
} finally {
   
    Unregister-Event -SourceIdentifier $OnCreated.Name
    $FileSystemWatcher.Dispose()
}

This works so far, except for the fact that it also creates a folder in the target directory with the file name to be copied.
How do I change that so that he doesn't create this folder?

Many Thanks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top