9
votes

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.

3

3 Answers

1
votes

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()
}
-1
votes

You may need try to run the command line as Administrator.

-3
votes

Masi, Powershell copy-item function is not really that great IMO. Why not use robocopy/Powershell hybrid here?

Example:

$source = "C:\temp"

$destination ="\\\RemoteServer\Temp"

robocopy $source $destination /s /mt:8