powershellprofilecopy-item

Copy-Item error and how to catch access is denied


I have a script that backs up User Profiles Documents.

The code is:

$sourceFolder = "C:\Users\username\Documents"
$backupFolder = "C:\temp\Backup\profilefolders\username\Documents"
Copy-Item -Path $sourceFolder -Destination $backupFolder -Recurse -Force

However, When the cop hits a folder My Music, My Pictures, My Videos I am getting understandably an error Access to the path 'C:\Users\username\Documents\My Music' is denied. Since the folders are only shortcuts to folders in the users root folder.

I can add -ErrorAction SilentlyContinue to have the errors ignored.

But I want to show an error but not like this in red:

Copy-Item : Access to the path 'C:\Users\username\Documents\My Music' is denied.
At C:\Temp\scripts\folderbackups.ps1:60 char:13
+             Copy-Item -Path $sourceFolder -Destination $backupFolder  ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (My Music:DirectoryInfo) [Copy-Item], UnauthorizedAccessException
    + FullyQualifiedErrorId : CopyDirectoryInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand

Is there a quick way to just have an error message that just shows with background in red:

"Error: access to C:\Users\username\Documents\My Music denied and not backed up."

Obviously use a variable that picks up the location.

Cheers


Solution

  • To put it all together:

    Copy-Item -Path $sourceFolder -Destination $backupFolder -Recurse -Force 2>&1 | 
      ForEach-Object { 
        Write-Host -BackgroundColor Red "Error: access to $($_.TargetObject) denied and not backed up." 
      }
    

    Note: