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
Use redirection 2>&1
to merge the non-terminating error that occur into the success output stream.
Given that Copy-Item
normally produces no (success) output, you can therefore assume that any objects emitted are errors, specifically instances of type System.Management.Automation.ErrorRecord
.
You can process these objects in a ForEach-Object
script block, craft a custom message and pass it to Write-Host
with -BackgroundColor
red.
$_.TargetObject
contains the offending path.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: