External USB HDD vs alternate-target-paths + alternate-destination-marker

Hello!

I have two different sets to alternate backups on two different disks (rolling each day).
(Duplicati - 2.0.8.1_beta_2024-05-07)

I added those options:
Set 1

--alternate-target-paths=*:\_SAUVEGARDES\D
--alternate-destination-marker=backup_here.txt

Set 2

--alternate-target-paths=*:\_SAUVEGARDES\D
--alternate-destination-marker=backup_here2.txt

Strangely, sometimes I need to change the usb port to be able to backup. Duplicati say “marker not found”. There is a file with this name, sure.

Logs:

Failed: Le fichier de marquage backup_here.txt n'a  été trouvé dans aucune des destinations : G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
Details: Duplicati.Library.Interface.UserInformationException: Le fichier de marquage backup_here.txt n'a  été trouvé dans aucune des destinations : G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
   à Duplicati.Library.Backend.File..ctor(String url, Dictionary`2 options)
--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à Duplicati.Library.DynamicLoader.BackendLoader.BackendLoaderSub.GetBackend(String url, Dictionary`2 options)
   à Duplicati.Library.Main.BackendManager..ctor(String backendurl, Options options, IBackendWriter statwriter, LocalDatabase database)
   à Duplicati.Library.Main.Operation.BackupHandler.<RunAsync>d__20.MoveNext()
--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à CoCoL.ChannelExtensions.WaitForTaskOrThrow(Task task)
   à Duplicati.Library.Main.Controller.<>c__DisplayClass14_0.<Backup>b__0(BackupResults result)
   à Duplicati.Library.Main.Controller.RunAction[T](T result, String[]& paths, IFilter& filter, Action`1 method)

Log data:
2024-05-26 21:31:25 +02 - [Error-Duplicati.Library.Main.Operation.BackupHandler-FatalError]: Fatal error
Duplicati.Library.Interface.UserInformationException: Le fichier de marquage backup_here.txt n'a  été trouvé dans aucune des destinations : G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
   à Duplicati.Library.Backend.File..ctor(String url, Dictionary`2 options)
--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à Duplicati.Library.DynamicLoader.BackendLoader.BackendLoaderSub.GetBackend(String url, Dictionary`2 options)
   à Duplicati.Library.Main.BackendManager..ctor(String backendurl, Options options, IBackendWriter statwriter, LocalDatabase database)
   à Duplicati.Library.Main.Operation.BackupHandler.<RunAsync>d__20.MoveNext()

What can I do?

Thank you.
bm

Welcome to the forum @18i

How often? Any pattern?

Quite strange. Unplugging and plugging in to same port (and waiting awhile) still errors?
Does the other port seem to put the drive at the same drive letter as reusing same port?

On what drive letter? For example. check it after the error. You can also see if Duplicati sees it elsewhere, for example if you go to the Destination screen. Note Windows drive letters are per-login, meaning if Duplicati is a Windows service or an elevated admin, letter might be different.

Hello @ts678,
It’s happen ±3/5 times and plug it again in the same port give the same result.
Duplicati is installed trough Chocolatey. As I can see, it’s not installed as a service.
For the first set, the destination is G: and for the second it’s H:.

I just realize by checking that the 2 conf aren’t identical: the second is missing the directory.
It’s corrected to try it as this.
Thank you :slight_smile:

Missing the directory on the Destination path or --alternate-target-paths?

I think the second makes the first be ignored though. There’s also a bug in how it’s maintained.

Destination screen advanced options, tend to get lost on next job edit. Use the Options screen.

I’m not sure if any of this explains your error message though, but that’s still being investigated.

You also have some specific observations requested to do the next time the problem comes up.

It’s missing the destination path but works fine so your your explanation seems to be the right one.
I keep it on watching and I will report the log (in english this time) here.
Thank you.

Hello!
Since my last message, I have 11 backups for 1 error on last saturday.
Since there isn’t any difference with the two external drives I start to think about hardware problem with the mobo. We experienced it in the same way as previously: just replug, ok.
Logs from the task:

Failed: The marker file "[marker_file.txt]" was not found in any of the examined destinations: H:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
Details: Duplicati.Library.Interface.UserInformationException: The marker file "[marker_file.txt]" was not found in any of the examined destinations: H:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
   à Duplicati.Library.Backend.File..ctor(String url, Dictionary`2 options)
--- End of stack trace from previous location at which exception was raised ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à Duplicati.Library.DynamicLoader.BackendLoader.BackendLoaderSub.GetBackend(String url, Dictionary`2 options)
   à Duplicati.Library.Main.BackendManager..ctor(String backendurl, Options options, IBackendWriter statwriter, LocalDatabase database)
   à Duplicati.Library.Main.Operation.BackupHandler.<RunAsync>d__20.MoveNext()
--- End of stack trace from previous location at which exception was raised ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à CoCoL.ChannelExtensions.WaitForTaskOrThrow(Task task)
   à Duplicati.Library.Main.Controller.<>c__DisplayClass14_0.<Backup>b__0(BackupResults result)
   à Duplicati.Library.Main.Controller.RunAction[T](T result, String[]& paths, IFilter& filter, Action`1 method)

DeletedFiles: 0
DeletedFolders: 0
ModifiedFiles: 0
ExaminedFiles: 0
OpenedFiles: 0
AddedFiles: 0
SizeOfModifiedFiles: 0
SizeOfAddedFiles: 0
SizeOfExaminedFiles: 0
SizeOfOpenedFiles: 0
NotProcessedFiles: 0
AddedFolders: 0
TooLargeFiles: 0
FilesWithError: 0
ModifiedFolders: 0
ModifiedSymlinks: 0
AddedSymlinks: 0
DeletedSymlinks: 0
PartialBackup: False
Dryrun: False
MainOperation: Backup
ParsedResult: Fatal
Interrupted: False
Fatal: True
Version: 2.0.8.1 (2.0.8.1_beta_2024-05-07)
EndTime: 17/08/2024 23:07:31 (1723928851)
BeginTime: 17/08/2024 23:07:30 (1723928850)
Duration: 00:00:00.3098636
MessagesActualLength: 1
WarningsActualLength: 0
ErrorsActualLength: 2
LimitedMessages: [
    2024-08-17 23:07:30 +02 - [Information-Duplicati.Library.Main.Controller-StartingOperation]: The operation Backup has started
]
LimitedWarnings: []
LimitedErrors: [
    2024-08-17 23:07:31 +02 - [Error-Duplicati.Library.Main.Operation.BackupHandler-FatalError]: Fatal error
UserInformationException: The marker file "[marker_file.txt]" was not found in any of the examined destinations: H:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D,
    2024-08-17 23:07:31 +02 - [Error-Duplicati.Library.Main.Controller-FailedOperation]: The operation Backup has failed with error: The marker file "[marker_file.txt]" was not found in any of the examined destinations: H:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
UserInformationException: The marker file "[marker_file.txt]" was not found in any of the examined destinations: H:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
]
Log data:
2024-08-17 23:07:31 +02 - [Error-Duplicati.Library.Main.Operation.BackupHandler-FatalError]: Fatal error
Duplicati.Library.Interface.UserInformationException: The marker file "[marker_file.txt]" was not found in any of the examined destinations: H:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
   à Duplicati.Library.Backend.File..ctor(String url, Dictionary`2 options)
--- End of stack trace from previous location at which exception was raised ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à Duplicati.Library.DynamicLoader.BackendLoader.BackendLoaderSub.GetBackend(String url, Dictionary`2 options)
   à Duplicati.Library.Main.BackendManager..ctor(String backendurl, Options options, IBackendWriter statwriter, LocalDatabase database)
   à Duplicati.Library.Main.Operation.BackupHandler.<RunAsync>d__20.MoveNext()
2024-08-17 23:07:31 +02 - [Error-Duplicati.Library.Main.Controller-FailedOperation]: The operation Backup has failed with error: The marker file "[marker_file.txt]" was not found in any of the examined destinations: H:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
Duplicati.Library.Interface.UserInformationException: The marker file "[marker_file.txt]" was not found in any of the examined destinations: H:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
   à Duplicati.Library.Backend.File..ctor(String url, Dictionary`2 options)
--- End of stack trace from previous location at which exception was raised ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à Duplicati.Library.DynamicLoader.BackendLoader.BackendLoaderSub.GetBackend(String url, Dictionary`2 options)
   à Duplicati.Library.Main.BackendManager..ctor(String backendurl, Options options, IBackendWriter statwriter, LocalDatabase database)
   à Duplicati.Library.Main.Operation.BackupHandler.<RunAsync>d__20.MoveNext()
--- End of stack trace from previous location at which exception was raised ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à CoCoL.ChannelExtensions.WaitForTaskOrThrow(Task task)
   à Duplicati.Library.Main.Controller.<>c__DisplayClass14_0.<Backup>b__0(BackupResults result)
   à Duplicati.Library.Main.Controller.RunAction[T](T result, String[]& paths, IFilter& filter, Action`1 method)

Regards,
bm

Hello,

On 08.28, there were an error with the second set to the second external hdd.
Here it is:

Failed: The marker file "backup_here.txt" was not found in any of the examined destinations: G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
Details: Duplicati.Library.Interface.UserInformationException: The marker file "backup_here.txt" was not found in any of the examined destinations: G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
   à Duplicati.Library.Backend.File..ctor(String url, Dictionary`2 options)
--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à Duplicati.Library.DynamicLoader.BackendLoader.BackendLoaderSub.GetBackend(String url, Dictionary`2 options)
   à Duplicati.Library.Main.BackendManager..ctor(String backendurl, Options options, IBackendWriter statwriter, LocalDatabase database)
   à Duplicati.Library.Main.Operation.BackupHandler.<RunAsync>d__20.MoveNext()
--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à CoCoL.ChannelExtensions.WaitForTaskOrThrow(Task task)
   à Duplicati.Library.Main.Controller.<>c__DisplayClass14_0.<Backup>b__0(BackupResults result)
   à Duplicati.Library.Main.Controller.RunAction[T](T result, String[]& paths, IFilter& filter, Action`1 method)

DeletedFiles: 0
DeletedFolders: 0
ModifiedFiles: 0
ExaminedFiles: 0
OpenedFiles: 0
AddedFiles: 0
SizeOfModifiedFiles: 0
SizeOfAddedFiles: 0
SizeOfExaminedFiles: 0
SizeOfOpenedFiles: 0
NotProcessedFiles: 0
AddedFolders: 0
TooLargeFiles: 0
FilesWithError: 0
ModifiedFolders: 0
ModifiedSymlinks: 0
AddedSymlinks: 0
DeletedSymlinks: 0
PartialBackup: False
Dryrun: False
MainOperation: Backup
ParsedResult: Fatal
Interrupted: False
Fatal: True
Version: 2.0.8.1 (2.0.8.1_beta_2024-05-07)
EndTime: 28/08/2024 22:53:15 (1724878395)
BeginTime: 28/08/2024 22:53:15 (1724878395)
Duration: 00:00:00.3769425
MessagesActualLength: 1
WarningsActualLength: 0
ErrorsActualLength: 2
LimitedMessages: [
    2024-08-28 22:53:15 +02 - [Information-Duplicati.Library.Main.Controller-StartingOperation]: The operation Backup has started
]
LimitedWarnings: []
LimitedErrors: [
    2024-08-28 22:53:15 +02 - [Error-Duplicati.Library.Main.Operation.BackupHandler-FatalError]: Fatal error
UserInformationException: The marker file "backup_here.txt" was not found in any of the examined destinations: G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D,
    2024-08-28 22:53:15 +02 - [Error-Duplicati.Library.Main.Controller-FailedOperation]: The operation Backup has failed with error: The marker file "backup_here.txt" was not found in any of the examined destinations: G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
UserInformationException: The marker file "backup_here.txt" was not found in any of the examined destinations: G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
]
Log data:
2024-08-28 22:53:15 +02 - [Error-Duplicati.Library.Main.Operation.BackupHandler-FatalError]: Fatal error
Duplicati.Library.Interface.UserInformationException: The marker file "backup_here.txt" was not found in any of the examined destinations: G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
   à Duplicati.Library.Backend.File..ctor(String url, Dictionary`2 options)
--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à Duplicati.Library.DynamicLoader.BackendLoader.BackendLoaderSub.GetBackend(String url, Dictionary`2 options)
   à Duplicati.Library.Main.BackendManager..ctor(String backendurl, Options options, IBackendWriter statwriter, LocalDatabase database)
   à Duplicati.Library.Main.Operation.BackupHandler.<RunAsync>d__20.MoveNext()
2024-08-28 22:53:15 +02 - [Error-Duplicati.Library.Main.Controller-FailedOperation]: The operation Backup has failed with error: The marker file "backup_here.txt" was not found in any of the examined destinations: G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
Duplicati.Library.Interface.UserInformationException: The marker file "backup_here.txt" was not found in any of the examined destinations: G:\_SAUVEGARDES\D\, C:\_SAUVEGARDES\D, D:\_SAUVEGARDES\D, E:\_SAUVEGARDES\D, F:\_SAUVEGARDES\D
   à Duplicati.Library.Backend.File..ctor(String url, Dictionary`2 options)
--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à Duplicati.Library.DynamicLoader.BackendLoader.BackendLoaderSub.GetBackend(String url, Dictionary`2 options)
   à Duplicati.Library.Main.BackendManager..ctor(String backendurl, Options options, IBackendWriter statwriter, LocalDatabase database)
   à Duplicati.Library.Main.Operation.BackupHandler.<RunAsync>d__20.MoveNext()
--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
   à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   à CoCoL.ChannelExtensions.WaitForTaskOrThrow(Task task)
   à Duplicati.Library.Main.Controller.<>c__DisplayClass14_0.<Backup>b__0(BackupResults result)
   à Duplicati.Library.Main.Controller.RunAction[T](T result, String[]& paths, IFilter& filter, Action`1 method)

(On side of this, how to set full english for logs?)

…/…

An other on 08.30, there were an error with the first set set to the first external hdd.
Here it is:
logs are to big to be here and extensions .log or .txt are not allowed so:
https://paste.opensuse.org/pastes/1365b7086b15

(On side of this, how to set full english for logs?)

Have a good day,
bm

Hello,
On 9.08, I had two errors more.
Solved on the 3rd try after unplug/replug.

Which information should I add here to help?

Regards,

If it’s the above, that’s beyond Duplicati support, but there’s not enough info yet, for example:

Basically, Duplicati error may be because the file wasn’t seen when it looked. I asked for status after, but you could also check status before. Or do you know the file was there before backup?

What is the timing of all this? It probably takes a little while after plugging in USB for the drive to start, and files to appear. If you leave it plugged in and idle for a long time, drive may spin down.

Scripting options such as run-script-before can try to check status of the drives before a backup.

Windows Batch Scripting: Stdin, Stdout, Stderr explains how you can redirect output of, say, the appropriate dir commands to see what’s there. Be sure to redirect stderr into the log file as well.

Example Scripts shows how you can set a script exit code to control what Duplicati does after it.

Hello, and many thanks for your answer.

Spoiler: I’m almost totally ignorant of powershell. I work nearly only on GNU/Linux so I get help with AI.

Since I have two rolling external drives, I added two scripts. The only difference is the name of the log file.
The goal is to test if an usb drive is mounted, have a letter (not c, d, e, f) and writable and finaly run the backup. I want this stop the task if no drive is detected (Duplicati part with --run-script-before-required)

There is the code:

function Check-USB-Drive {
    $logFilePath = "C:\Users\admin\testUSBhddext.log" #…1.log and …2.log

    if (Test-Path -Path $logFilePath) {
        Clear-Content -Path $logFilePath
    }

    $maxAttempts = 3
    $attempts = 0

    while ($attempts -lt $maxAttempts) {
        try {
            $drives = Get-WmiObject -Class Win32_LogicalDisk | Where-Object { $_.DriveType -eq 2 -and $_.DeviceID -notin @('C:', 'D:', 'E:', 'F:') } # those are local nvme and sata  drives

            if ($drives.Count -eq 0) {
                Write-Host "No USB drives found. Retrying in 10 seconds..."
                Add-Content -Path $logFilePath -Value "No USB drives found. Retrying in 10 seconds...`n"
                Start-Sleep -Seconds 10
                $attempts++
                continue
            }

            foreach ($drive in $drives) {
                $driveLetter = $drive.DeviceID
                $driveLabel = $drive.VolumeName
                $driveFreeSpace = [math]::Round($drive.FreeSpace / 1MB, 2)

                $testFilePath = "$driveLetter\test.txt"
                try {
                    New-Item -Path $testFilePath -ItemType File -Force -ErrorAction Stop
                    $isWritable = $true
                    Remove-Item -Path $testFilePath -Force
                } catch {
                    $isWritable = $false
                }

                if ($isWritable) {
                    $logMessage = "USB Drive mounted: $driveLetter ($driveLabel)`nFree space: $driveFreeSpace Mb`nWritable: Yes`n"
                } else {
                    $logMessage = "USB Drive mounted: $driveLetter ($driveLabel)`nFree space: $driveFreeSpace Mb`nWritable: No`n"
                }

                Add-Content -Path $logFilePath -Value $logMessage
                Write-Host $logMessage
            }

            break
        } catch {
            $errorMessage = "Error checking USB drives: $_`n"
            Add-Content -Path $logFilePath -Value $errorMessage
            Write-Host $errorMessage
        }
    }

    if ($attempts -eq $maxAttempts) {
        $errorMessage = "No USB drives found after $maxAttempts attempts.`n"
        Add-Content -Path $logFilePath -Value $errorMessage
        Write-Host $errorMessage
    }

    $exitCode = 0
    if ($attempts -eq $maxAttempts) {
        $exitCode = 1
    }
    $exitMessage = "Script execution completed with exit code: $exitCode`n"
    Add-Content -Path $logFilePath -Value $exitMessage
    Write-Host $exitMessage

    return $exitCode
}

$exitCode = Check-USB-Drive
Write-Host "Final exit code: $exitCode"
exit $exitCode

I added an option on each backup set:

  • set 1: --run-script-before-required C:\Users\admin\testUSBhddext1.ps=true
  • set 2: --run-script-before-required C:\Users\admin\testUSBhddext2.ps=true
    (=true was added by Duplicati)

What do think about?

Regards,

How did that get in? I don’t use it much either, so suggested (and linked to) batch file info.

C:\>dir "C:\_SAUVEGARDES\D\backup_here.txt"
The system cannot find the path specified.

C:\>dir "D:\_SAUVEGARDES\D\backup_here.txt"
The device is not ready.

are some example errors which go to stderr. Redirection is similar to Linux bash, so maybe

>> <logfile> 2>&1

if you want to make an appending log. You can throw in an echo %DATE% %TIME% if it helps.

Hello,
I used mistral.ai (mod. Large2).
It’s quite a fun exercise to do, because it requires you to clearly define the context and the goal. Think through the problem step by step, explaining it precisely to circumscribe the field of response as much as possible.
That’s what we usually do, but the bonus is that it gives us perspective on our own logic.
State the obvious, we need to have a minimum of knowledge in order to succeed quickly.

The hardest part was getting it to correct the errors during debugging.
AIs have a nasty tendency to make things up when they don’t know or to support an answer that is obviously wrong. This is not to be trusted…
For example, on the first run, no log file was created while this was clearly part of the statement. I had to make it correct the script 4 or 5 times before it worked as expected. Then, I added “functions” while checking that the rest was not modified.
To debug, I simply used Win PowerShell ISE.

I added date and time as you adviced (stupidly forgot that :yum:) and a block to determine whether a usb disk is physically connected or not.

function Check-USB-Drive {
    # Define the log file path
    $logFilePath = "C:\Users\xadmin\testUSBhddext1.log"

    # Check if the log file exists and clear it if it does
    if (Test-Path -Path $logFilePath) {
        Clear-Content -Path $logFilePath
    }

    # Define the maximum number of attempts
    $maxAttempts = 3
    $attempts = 0

    # Loop to check for USB drives
    while ($attempts -lt $maxAttempts) {
        try {
            # Get USB drives
            $drives = Get-WmiObject -Class Win32_LogicalDisk | Where-Object { $_.DriveType -eq 2 -and $_.DeviceID -notin @('C:', 'D:', 'E:', 'F:') }

            # Check if any USB drives are found
            if ($drives.Count -eq 0) {
                $message = "No USB drives found. Retrying in 10 seconds..."
                $logMessage = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $message"
                Add-Content -Path $logFilePath -Value "$logMessage`n"
                Start-Sleep -Seconds 10
                $attempts++
                continue
            }

            # Iterate through each USB drive found
            foreach ($drive in $drives) {
                $driveLetter = $drive.DeviceID
                $driveLabel = $drive.VolumeName
                $driveFreeSpace = [math]::Round($drive.FreeSpace / 1MB, 2)

                # Test file path
                $testFilePath = "$driveLetter\test.txt"

                # Test if the drive is writable
                try {
                    New-Item -Path $testFilePath -ItemType File -Force -ErrorAction Stop
                    $isWritable = $true
                    Remove-Item -Path $testFilePath -Force
                } catch {
                    $isWritable = $false
                }

                # Create the log message
                $logMessage = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - USB Drive mounted: $driveLetter ($driveLabel)`nFree space: $driveFreeSpace Mb`nWritable: $isWritable`n"

                # Add the message to the log file
                Add-Content -Path $logFilePath -Value $logMessage
            }

            # Exit the loop if USB drives are found
            break
        } catch {
            $errorMessage = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Error checking USB drives: $_`n"
            Add-Content -Path $logFilePath -Value $errorMessage
        }
    }

    # Check if the maximum number of attempts is reached
    if ($attempts -eq $maxAttempts) {
        $errorMessage = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - No USB drives found after $maxAttempts attempts.`n"
        Add-Content -Path $logFilePath -Value $errorMessage

        # List USB drives using WMI
        $usbDrives = Get-WmiObject -Class Win32_DiskDrive | Where-Object { $_.InterfaceType -eq 'USB' }
        $usbDrivesMessage = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Listing USB drives:`n"
        foreach ($usbDrive in $usbDrives) {
            $usbDrivesMessage += "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - DeviceID: $($usbDrive.DeviceID), Model: $($usbDrive.Model), Size: $($usbDrive.Size) bytes`n"
        }
        Add-Content -Path $logFilePath -Value $usbDrivesMessage
    }

    # Define the exit code
    $exitCode = 0
    if ($attempts -eq $maxAttempts) {
        $exitCode = 1
    }

    # Add the final message to the log file
    $exitMessage = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Script execution completed with exit code: $exitCode`n"
    Add-Content -Path $logFilePath -Value $exitMessage

    # Return the exit code
    return $exitCode
}

# Call the function and get the exit code
$exitCode = Check-USB-Drive
exit $exitCode

For now, I’m waiting about the next try from my client.
Best regards,