首页 > 解决方案 > Powershell 复制项问题

问题描述

我正在尝试将用户的配置文件从另一个驱动器复制到我的 C: 驱动器。我把它记下来了,但我遇到了两个我一直在努力解决的问题,但没有什么对我有用。

$user="JohnDoe"

Copy-Item -Path "H:\$user\Contacts" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force
Copy-Item -Path "H:\$user\Desktop" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 
Copy-Item -Path "H:\$user\Documents" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 
Copy-Item -Path "H:\$user\Downloads" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 
Copy-Item -Path "H:\$user\Favorites" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 
Copy-Item -Path "H:\$user\Links" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 
Copy-Item -Path "H:\$user\Music" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 
Copy-Item -Path "H:\$user\Pictures" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 
Copy-Item -Path "H:\$user\Saved Games" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 
Copy-Item -Path "H:\$user\Searches" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 
Copy-Item -Path "H:\$user\Start Menu" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 
Copy-Item -Path "H:\$user\Videos" -Destination C:\Users\user\Desktop\UserProfile\$user -recurse -Force 

当我运行代码时,发生的第一个问题是任何首先复制的文件夹,它的所有内容都将放在

 C:\Users\user\Desktop\UserProfile\$user

例如,在我的代码中,来自原始 H: Drive 的“Contacts”文件夹中的任何内容都将被复制到 C:Drive,而不是在“Contacts”文件夹中,而是在路径位置

 C:\Users\user\Desktop\UserProfile\$user

第二个问题是在所有文件夹中创建了 $RECYCLE.BIN。

在 C:Drive 路径文件夹内


在 C:Drive 路径文件夹\Favorites 内

一些帮助将不胜感激。

标签: powershellcopy-item

解决方案


在这里,我使用了一个名为 Splatting 的功能将参数哈希表应用于函数:

$user = 'JohnDoe'

$ciArgs = @{
    Path        = "H:\$user"
    Destination = '~\Desktop\UserProfile\'
    Container   = $true
    Recurse     = $true
    Force       = $true
    Exclude     = '*$RECYCLE.BIN*'
}
Copy-Item @ciArgs

这会将文件夹完整复制$user到您的UserProfile文件夹,跳过回收站隐藏文件夹。


推荐阅读