UnauthorizedAccessException using Copy-Item on a remote file server

I am trying to copy about 10 folders, each of which contains a ~ 3KB .txt file to a deleted file with a delay of several seconds. I am using Powershells Copy-Item as follows:

 try { Copy-Item -Path $source -Destination $destination -Recurse -ErrorAction Stop } catch { Write-Error $_.Exception.ToString() } 

The user on which the script is running has read, write, and execute permissions on the shared file server and on the local source.

At first launch, the destination folder is empty. Everything is working fine. At the second start, files and folders already exist. Therefore, before running the code above, I first run the test using Test-Path , and if there is a delete in the folder 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() } 

No one is editing these files. However, when I run the script a dozen times, from time to time, for some reason I don’t understand, I suddenly get UnauthorizedAccessException errors for some of the folders when copying. Exact error:

System.UnauthorizedAccessException: access denied ---> System.ComponentModel.Win32Exception: access is denied in Microsoft.PowerShell.Commands.FileSystemProvider.NativeDirectoryExists (String path) in System.Management.Automation.SessionStateInternal.IsItemContainer (pathmdletter providerCmdletter CmdletProviderContext

note: I get these errors AFTER deleting old files on the remote file server.

+9
source share
2 answers

This is an old post, but maybe you can benefit from it. You do not need to delete in advance. You can simply use -Force to override existing files.

 try { Copy-Item -Path $source -Destination $destination -Recurse -ErrorAction Stop -Force } catch { Write-Error $_.Exception.ToString() } 
0
source share

Masi, the copy function of Powershell instances is actually not that big IMO. Why not use the robocopy / Powershell hybrid here?

Example:

 $source = "C:\temp" $destination ="\\\RemoteServer\Temp" robocopy $source $destination /s /mt:8 
-3
source share

All Articles