Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Path to CSV file
- $csvFile = "C:\Users\J2897\Code\PowerShell\DriveSync\DeviceMapping.csv"
- # Function to perform device scan and output details
- function Scan-Devices {
- try {
- $devices = Import-Csv -Path $csvFile
- $pnpDevices = Get-WmiObject -Class Win32_PnPEntity | Where-Object { $_.DeviceID -like "USBSTOR*" }
- $diskDrives = Get-WmiObject -Class Win32_DiskDrive | Where-Object { $_.PNPDeviceID -like "USBSTOR*" }
- Clear-Host
- Write-Host "`n--- DEBUG OUTPUT ---"
- Write-Host "Detected PnP Devices: $($pnpDevices.Count)"
- Write-Host "Detected Disk Drives: $($diskDrives.Count)"
- Write-Host "`n--- STARTING DEVICE SCAN ---"
- foreach ($device in $devices) {
- $csvDeviceID = $device.DeviceID
- $sourceDir = $device.SourceDirectory
- $targetDir = $device.TargetDirectory
- Write-Host "`nDevice ID: $csvDeviceID"
- Write-Host " Source: $sourceDir"
- Write-Host " Target: $targetDir"
- $pnpDevice = $pnpDevices | Where-Object { $_.DeviceID -eq $csvDeviceID }
- if (-not $pnpDevice) {
- Write-Host " -> Device not found."
- continue
- }
- $diskDrive = $diskDrives | Where-Object { $_.PNPDeviceID -eq $csvDeviceID }
- if (-not $diskDrive) {
- Write-Host " -> No disk drive found."
- continue
- }
- Write-Host " -> Found disk drive: $($diskDrive.DeviceID)"
- $partitions = $diskDrive.GetRelated("Win32_DiskPartition")
- if (-not $partitions) {
- Write-Host " -> No partitions found."
- continue
- }
- $driveLetters = @()
- foreach ($partition in $partitions) {
- $logicalDisks = $partition.GetRelated("Win32_LogicalDisk")
- if ($logicalDisks) {
- foreach ($disk in $logicalDisks) {
- $driveLetters += $disk.DeviceID
- Write-Host " -> Drive letter: $($disk.DeviceID)"
- }
- } else {
- Write-Host " -> No logical disks found for partition $($partition.DeviceID)"
- }
- }
- if ($driveLetters.Count -eq 0) {
- Write-Host " -> No drive letter found"
- continue
- }
- # Execute Robocopy properly with correct parameters
- # Execute Robocopy properly with correct parameters
- foreach ($letter in $driveLetters) {
- $sourcePath = "$letter\$sourceDir"
- if (Test-Path $sourcePath) {
- Write-Host " -> Syncing $sourcePath to $targetDir"
- # Ensure the target directory exists before executing Robocopy
- if (-not (Test-Path $targetDir)) {
- Write-Host " -> Target directory does not exist. Creating: $targetDir"
- New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
- }
- # Use Join-Path to prevent double backslashes in log path
- $logPath = Join-Path -Path $targetDir -ChildPath "RobocopyLog.txt"
- # Normalize backslashes in paths to prevent issues
- $sourceQuoted = "`"$($sourcePath -replace '\\', '\\')`""
- $targetQuoted = "`"$($targetDir -replace '\\', '\\')`""
- $logQuoted = "`"$($logPath -replace '\\', '\\')`""
- # Robocopy arguments with corrected log path
- $robocopyArgs = @(
- $sourceQuoted,
- $targetQuoted,
- "/E", # Copy all subdirectories, including empty ones
- "/COPY:DAT", # Correct syntax for data, attributes, timestamps
- "/R:3", # Retry 3 times on failure
- "/W:5", # Wait 5 seconds between retries
- "/LOG+:$logQuoted", # Append log output
- "/TEE" # Display output in console as well
- )
- # Execute Robocopy properly using call operator '&'
- try {
- Write-Host "`n[EXECUTING]: Robocopy $($robocopyArgs -join ' ')"
- & "Robocopy" $robocopyArgs
- } catch {
- Write-Host "Failed to execute Robocopy: $_"
- }
- } else {
- Write-Host " -> Source directory not found: $sourcePath"
- }
- }
- }
- } catch {
- Write-Host "An error occurred: $_"
- }
- }
- # Remove any existing event subscriptions with the same SourceIdentifier
- Get-EventSubscriber | Where-Object { $_.SourceIdentifier -eq "USBInserted" } | Unregister-Event
- # Register WMI event for USB disk drive insertions
- Register-WmiEvent -Query "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_DiskDrive' AND TargetInstance.InterfaceType = 'USB'" `
- -SourceIdentifier "USBInserted"
- Write-Host "`nMonitoring for USB device insertions. Press Ctrl+C to exit."
- # Use trap to handle Ctrl+C
- trap {
- Write-Host "`n[INFO] Script interrupted by user."
- break
- }
- # Wait for events and process them synchronously
- try {
- while ($true) {
- $event = Wait-Event -SourceIdentifier "USBInserted"
- Write-Host "`n[EVENT] USB device inserted."
- Scan-Devices
- Remove-Event -EventIdentifier $event.EventIdentifier
- }
- } catch {
- Write-Host "An error occurred: $_"
- } finally {
- Write-Host "`n[INFO] Cleaning up and exiting..."
- Unregister-Event -SourceIdentifier "USBInserted"
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement