PowerShell Copy-Item whilst excluding files and folders from an array list

I'm trying to create a simple PowerShell script that copies the contents of a Windows user profile to a new location but excluding specific files and folders such as AppData and the NTUSER files.

Below is my script and I've used variables to reduce a bit of clutter.

### REPLACE `-Value` property below ###
# User profile path
Set-Variable -Name "User_Profile" -Value "C:\Users\John"
# Temporary Destination path
Set-Variable -Name "Temp_Destination" -Value "C:\Backup"

Write-Output "Copying User Profile Files/Folders to '$Temp_Destination'"
Write-Output ""
Start-Sleep -s 2

$ExcludedContent = @(
    'AppData'
    'Application Data'
    'Cookies'
    'Local Settings'
    'MicrosoftEdgeBackups'
    'My Documents'
    'Documents\My Music'
    'Documents\My Pictures'
    'Documents\My Videos'
    'NetHood'
    'PrintHood'
    'Recent'
    'SendTo'
    'Start Menu'
    'Templates'
    'desktop.ini'
    'NTUSER*'
    'ntuser'
)

foreach ($Exclude in $ExcludedContent) {
    Write-Output "`$Exclude` has been excluded from the operation"
    
    Copy-Item -Path $User_Profile\* -Exclude $Exclude -Destination $Temp_Destination -Recurse -Force
}

Start-Sleep -s 5

UPDATE 1

I have taken the idea of using the Get-Item cmdlet to pipe the data into the Copy-Item cmdlet. Everything now works except for the three paths I have in my excluded paths array:

  • "Documents\My Music"
  • "Documents\My Pictures"
  • "Documents\My Videos"

It simply comes back with:

Copy-Item : Access to the path 'C:\Users\John\Documents\My Music' is denied.
At C:\Copy or Move Userprofile to new location.ps1:63 char:67
+ ... dedContent -Force | Copy-Item -Destination $Temp_Destination -Recurse
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (My Music:DirectoryInfo) [Copy-Item], UnauthorizedAccessException
    + FullyQualifiedErrorId : CopyDirectoryInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
Get-Item -Path $User_Profile\* -Exclude $ExcludedContent -Force | Copy-Item -Destination $Temp_Destination -Recurse

Solution 1:

Does this help? - Replace your foreach ($Exclude in $ExcludedContent) {...} section with this

get-item -Path $User_Profile* -Exclude $ExcludedContent |foreach { write-output "Copying $" copy-item -path $ -Destination $Temp_Destination -Recurse -Force }