使用 Powershell 将文件复制到当前登录的用户和将来登录的用户

使用 Powershell 将文件复制到当前登录的用户和将来登录的用户

我想创建一个脚本,将文件复制到所有用户配置文件,包括已登录的用户和登录 Windows 10 PC 的新用户。文件应复制到的位置是 Users\username\AppData\Roaming

请帮助不擅长使用 powershell 的人

这是我当前的脚本。它将复制到现有配置文件,但我需要为每次登录的新用户添加要复制的行

$Source = '\\FileShare\FancyConfigurationFiles\Config.xml' 
$Destination = 'C:\users*\AppData\Roaming\' 
Get-ChildItem $Destination | ForEach-Object {Copy-Item -Path $Source -Destination $_ -Force}

答案1

C:\Users\Default\ 包含用于为登录到计算机的任何帐户创建配置文件文件夹的文件和设置,这些帐户在 C:\Users\ 中尚未有配置文件文件夹

如果您希望将文件包含在任何新登录的配置文件中,请将它们放在此目录结构内的所需位置。

对于已登录到计算机且具有配置文件文件夹的帐户,将文件放入 .\Default\ 不会产生任何变化。对于这些帐户,您可以手动或通过脚本将文件放入所需文件夹,或者您可以删除本地配置文件文件夹(这会导致本地保存的所有数据丢失),这意味着配置文件文件夹将在下次登录时从 .\Default\ 文件夹创建。

答案2

我首先要询问注册表配置文件在哪里,因为理论上配置文件是可以自定义的。从这个角度来看,每个配置文件中文件夹的位置也是可以自定义的AppData\Roaming,因此为了全面起见,我们也应该考虑到这一点。

# Get the list of profile paths from the registry; since they theoretically can be customized.
$profileListReg = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'

# This filters out short SIDs (such as the system account)
$profilesReg = Get-ChildItem $profileListReg | Where-Object { $_.Name.Split('-').Count -gt 4 }

$userProfiles = @{}

# Add Default Profile to hashtable
foreach ($profileReg in $profilesReg) {
    $userProfiles.Add($profilesReg.PSChildName, (Get-ItemProperty ('Registry::{0}' -f $profileReg.Name)).ProfileImagePath)
}

# Add Default Profile to hashtable
#   This will cover new users getting the file
$userProfiles.Add('.DEFAULT', (Get-ItemProperty $profileListReg).Default)

$source = '\\FileShare\FancyConfigurationFiles\Config.xml'
$userShellFoldersReg = 'Registry::HKEY_USERS\{0}\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'

# Copy Config to each Profile ...
foreach ($userProfile in $userProfiles.GetEnumerator()) {
    Write-Verbose "$($userProfile.Name): $($userProfile.Value)"

    $userShellFolders = Get-Item ($userShellFoldersReg -f $userProfile.Name)
    $appData = $userShellFolders.GetValue('AppData','','DoNotExpandEnvironmentNames')
    Write-Verbose "AppData: ${appData}"

    $destination = $appData.Replace('%USERPROFILE%', $userProfile.Value)
    Write-Verbose "Destination: ${destination}"

    Copy-Item -Path $Source -Destination ($destination -f $userProfile) -Force
}

您应该注释掉Copy-Item底部的行并打开详细程度($VerbosePreference = 'continue')来测试并确保这些详细消息看起来像您期望的那样。

注意:我不喜欢使用,HKLM:因为与注册表交互不会返回完整路径HKLM:,而是返回HKEY_LOCAL_MACHINE。因此,您必须替换这些字符串,或者知道您可以直接Registry::在它的前面添加并获取路径。无论如何,这更有用,因为并非所有配置单元都可用作 PS 驱动器。

相关内容