I'm trying to copy about 10 folders each containing a ~3KB .txt file onto a remote fileshare with some seconds latency. I'm using Powershells Copy-Item
like this:
try
{
Copy-Item -Path $source -Destination $destination -Recurse -ErrorAction Stop
}
catch
{
Write-Error $_.Exception.ToString()
}
The user running the script has read, write and execute permissions on the fileserver share and on the local source.
On first run, the destination folder is empty. Everything works fine.
On second run, the files and folders already exist. So before running the code above I first run a check using Test-Path
and in case the folder exists a delete using Remove-Item
like this:
try
{
if(Test-Path -Path $path -ErrorAction Stop)
{
Remove-Item -Recurse -Path $path -ErrorAction Stop
}
}
catch
{
Write-Error $_.Exception.ToString()
}
Nobody else edits those files. However, when running the script a dozent times, once in a while, for a reason I don't understand, i'm suddenly getting UnauthorizedAccessException errors for some of the folders while copying. The exact error is:
System.UnauthorizedAccessException: access denied ---> System.ComponentModel.Win32Exception: access denied in Microsoft.PowerShell.Commands.FileSystemProvider.NativeDirectoryExists(String path) in System.Management.Automation.SessionStateInternal.IsItemContainer(CmdletProvider providerInstance, String path, CmdletProviderContext context
please note: I'm getting those errors AFTER the deletion of the old files on the remote fileserver has compleated successfully.