Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnauthorizedAccessException using Copy-Item on remote fileserver

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.

like image 599
omni Avatar asked Jan 06 '13 15:01

omni


1 Answers

This is a years old post but maybe one can benefit from that. You don't have to remove beforehand. You can just use -Force to override existing files.

try
{
    Copy-Item -Path $source -Destination $destination -Recurse -ErrorAction Stop -Force
}
catch
{
    Write-Error $_.Exception.ToString()
}
like image 176
Zafer Balkan Avatar answered Oct 15 '22 13:10

Zafer Balkan