PowerShell Copy-Item 同时从数组列表中排除文件和文件夹

PowerShell Copy-Item 同时从数组列表中排除文件和文件夹

我正在尝试创建一个简单的 PowerShell 脚本,将 Windows 用户配置文件的内容复制到新位置,但不包括特定文件和文件夹,例如AppDataNTUSER文件。

下面是我的脚本,我使用了变量来减少一些混乱。

### 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

更新 1

我考虑使用 cmdletGet-Item将数据导入Copy-Itemcmdlet。现在,除了排除路径数组中的三条路径外,其他一切都正常:

  • “文档\我的音乐”
  • “文档\我的图片”
  • “文档\我的视频”

它只是返回:

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

答案1

这有帮助吗? - 用这个替换你的 foreach ($Exclude in $ExcludedContent) {...} 部分

get-item -Path $User_Profile* -Exclude $ExcludedContent |foreach { write-output "复制 $“复制项目-路径$-目的地 $Temp_Destination-递归-强制}

相关内容