ahussain
Goto Top

Problem mit Powershell Backup-Skript

Hallo allerseits,

ich habe mir ein kleines Backup-Skript geschrieben, welches beim Einstecken eines USB Sticks dessen Inhalte auf die Platte kopiert (also Backup von USB-Stick nach Festplatte).

Grundidee ist, dass beim Einstecken des Sticks das Backup gestartet wird.

Hier das Skript:
# [content:309121#1114968]

function CopyFolder($source, $dest) {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")  
	write-host "CopyFolder(${source},${dest})" -F Green  
	$Logfile     = "c:\temp\backup-usb-stick-$(get-date -f yyyy-MM-dd_hh-mm-ss).txt"  
	Robocopy $source $dest /MIR /TEE /R:2 /LOG:$Logfile | Out-Null
	[Windows.Forms.MessageBox]::Show("Die Dateien wurden von ${source} nach ${dest} gesichert.", "Sicherung", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information)   
} 

Get-EventSubscriber | Unregister-Event -Force
Register-WmiEvent -Query "Select * From __InstanceCreationEvent Within 1 where TargetInstance isa 'Win32_LogicalDisk' and TargetInstance.DriveType = 2" -SourceIdentifier 'RemovableDetector' -Action {  
	Get-EventSubscriber | Unregister-Event -Force
	
	$name = $Event.SourceEventArgs.NewEvent.TargetInstance.VolumeName
	$drive = $Event.SourceEventArgs.NewEvent.TargetInstance.DeviceID
	
	write-host "Wechselmedium '${name}' erkannt." -F Green  
	
	$volume = "USB STICK"  
	$target = "C:\Backup-USB_STICK"  
	if ($name -eq $volume) {
		write-host "Dateien von ${drive} nach ${target} kopieren ..." -F Green  
		CopyFolder $drive $target
	}
} | out-null
cls
write-host "Warten auf Wechselmedium ..." -F Green  
while($true){sleep 1}

Der USB-Stick wird vom Skript erkannt. Problem ist, dass die Funktion CopyFolder, welches das eigentliche Backup durchführt, nicht aufgerufen wird. Das Skript läuft bis zum Befehl
write-host "Dateien von ${drive} nach ${target} kopieren ..." -F Green  
... und dann ist Schluss.

Die Ausgabe ist:
Warten auf Wechselmedium ...
Wechselmedium 'USB STICK' erkannt.  
Dateien von D: nach C:\Backup-USB_STICK kopieren ...

Ich komme da irgendwie nicht weiter - was habe ich übersehen?

Gruß Abid

Content-Key: 358436

Url: https://administrator.de/contentid/358436

Printed on: April 19, 2024 at 08:04 o'clock

Mitglied: 134998
Solution 134998 Dec 16, 2017 updated at 10:43:34 (UTC)
Goto Top
The action runs in another context (event) which has no knowledge of the function CopyFolder because of scope. You need to declare the function as global for the event to be accessible..

Best regards
Tom
Member: ahussain
ahussain Dec 16, 2017 at 11:03:29 (UTC)
Goto Top
Thanks! Now it works... face-smile