User profile disks в windows server rds

User Profile Disks (UPD, диски профилей пользователей) позволяет хранить профиль каждого пользователей Remote Desktop Services (
%USERPROFILE%
) в отдельном виртуальном VHDX диске. Такой профиль подключается при входе пользователя в Windows и отключается при выходе (с сохранением изменений в профиле). User Profile Disks можно хранить на внешнем файловом ресурсе, благодаря чему пользователь может получить доступ к своему окружению (профили) при входе на любой сервер фермы RDS. UPD диски представляют собой альтернативу использованию технологий перемещаемых профилей (roaming profile) и перенаправления папок (folder redirection) в терминальных сценариях RDS.

В этой статье мы рассмотрим особенности настроить и использовать профили User Profile Disks на серверах с ролью Remote Desktop Services на Windows Server 2022/2019/2016/2012R2.

Содержание:

  • Настройка User Profile Disks в Windows Server RDS
  • VHDX файлы с UPD профилями пользователей RDS
  • Как расширить/сжать диск User Profile Disk с помощью PowerShell?
  • Временный профиль при использовании User Profile Disk в RDS

Настройка User Profile Disks в Windows Server RDS

Создайте общую сетевую папку для хранения файлов профилей UPD. Эту папку нужно разместить на любом файловом сервере за пределами фермы RDS ( рекомендуем расположить сетевую папку на кластере для обеспечения высокой доступности UPD профилей). В нашем примере, путь к такому каталогу будет выглядеть так:
\\srv01\RDSProfiles
.

Создайте в AD группу безопасности, в которую нужно включить все хосты в вашей RDS коллекции. МОжете создать группу с помощью графической консоли ADUC или с помощью PowerShell командлетов из модуля Active Directory for Windows PowerShell:
New-ADGroup mskRDSHCollection1 -path "OU=Groups,OU=MSK,OU=RU,DC=winitpro,DC=loc" -GroupScope Domain -PassThru –Verbose
Add-AdGroupMember -Identity mskRDSHCollection1 -Members msk-rds1$, msk-rds2$, msk-rds3$

Теперь предоставьте права Full Control на папку \\srv01\RDSProfiles для группы mskRDSHCollection1.

Настройки доступа к сетевой папке для хранения UPD профилей пользователей

Вы можете включить User Profile Disks в настройках коллекций Remote Desktop при ее создании. Если коллекция уже создана, найдите ее в консоли Server Manager и в верхнем левом углу выберите Tasks-> Edit Properties.

Настройка параметров коллекции RDS

Затем в разделе User Profile Disks включите опцию Enable user profile disks, укажите к созданной ранее сетевой папке (
\\srv01\RDSProfiles
) и задайте максимальный размер диска с профилем (пусть это будет 7 Гб). Сохраните изменения.

Включить User Profile Disks для коллекции RDS

Допустимо использовать пространство имен DFS для хранения UPD профилей DFS сервера. На DFS хостах нужно использовать Windows Server 2012 R2 или более новые версии. При использовании предыдущих версий Windows Server вы получите ошибку:

Unable to enable user disks on rVHDShare. Could not create template VHD.  Error Message: The network location "\\winitpro.ru\namespace\UPD1" is not available.

Вы можете проверить, что UPD включен для коллекции RDS и получить путь к каталогу, в котором хранятся профиля с помощью команды:

Get-RDSessionCollectionConfiguration -CollectionName mskCorpApp1 –UserProfileDisk

Get-RDSessionCollectionConfiguration: PowerShell настройки UserProfileDisk

Совет. Для каждой RDS коллекции создается только один vhdx файл с UPD профилем пользователя. Если пользователь подключается к хостам из двух разных RDS коллекций, для каждой из них будет создан отдельный vhdx файл.

По умолчанию UPD диск хранит все содержимое профиля пользователя. Вы можете исключить определенные папки из списка синхронизируемых каталогов. Если каталог исключен из профиля, изменения в нем не будут сохраняться в VHDX диске в сетевом каталоге. Доступные две опции:

  • Store all user settings and data on the user profile disk
  • Store only the following folders in the user profile disk

исключить некоторые папки пользователя из перемещаемого профиля UPD

При использовании RDS с UPD на Windows Server 2019/2016 со временем вы можете столкнуться со снижением производительности серверов, появления черного экрана при входе в RDP. Подробно проблема описана здесь. Рекомендуем сразу включить на всех RDS хостах параметр реестра DeleteUserAppContainersOnLogoff:

New-ItemProperty -Path “HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy” -Type DWord -Path -Name DeleteUserAppContainersOnLogoff -Value 1

VHDX файлы с UPD профилями пользователей RDS

После того, как вы изменили настройки коллекции и включили UPD, в целевом каталоге будет создан файл UVHD-template.vhdx.

Этот файл представляет собой шаблон виртуального диска с профилем пользователя. Когда новый пользователей подключается к серверу RDS по RDP, этот шаблон копируется и переименовывается в vhdx файл, содержащий в имени SID пользователя. Для каждого пользователя создается отдельный VHDX файл.

Совет. Информацию о событиях входа пользователей можно отслеживать в журнале Event Viewer -> Application (источник User Profile Service) и Applications and Services Logs -> -Microsoft -> Windows -> User Profile Service -> Operational.

UVHD файлы типа vhdx содержат профили пользователей UPD

Чтобы понять, какому пользователю принадлежит VHDX файл, нужно сопоставить имя UPD файла с именем пользователя. Можно вручную преобразовать SID в имя учетной записи с помощью командлета Get-ADUser:

Get-ADUser -Identity S-1-5-21-305647651-3952524288-2944781117-23711116

Или воспользуйтесь скриптом ShowUPDFolderDetails.ps1, который выводит имена UPD файлов и их владельцев:

$UPDShare = "\\srv01\RDSProfiles"
$UserProfiles = @()
$fc = new-object -com scripting.filesystemobject
$folder = $fc.getfolder($UPDShare)
"Username,SiD" >> export.csv
foreach ($i in $folder.files)
{
$sid = $i.Name
$sid = $sid.Substring(5,$sid.Length-10)
if ($sid -ne "template")
{
$securityidentifier = new-object security.principal.securityidentifier $sid
$user = ( $securityidentifier.translate( [security.principal.ntaccount] ) )
$UserProfile = New-Object PSObject -Property @{
UserName = $user
UPDFile=$i.Name
}

$UserProfiles += $UserProfile
}
}
$UserProfiles| select UserName, UPDFile

PowerShell скрипт - получить имена владельцев UVHD дисков в каталоге с UPD

Т.к. UPD профиль представляет собой обычный файл виртуального диска в формате VHDX, вы можете смонтировать его и просмотреть содержимое. Щелкните правой кнопкой по файлу и выберите Mount.

смонтировать UPD виртуальный диск пользователя

Как вы видите, содержимое VHDX диска представляет набор каталогов и файлов обычного профиля пользователя.

Содержимое диска с профилем

UPD профиль может монтируется в монопольном режиме. Это значит, что, если профиль пользователя сейчас подключен в RDS сессии пользователя или смонтирован вручную, вы не сможете открыть его с ошибкой: The file couldn’t be mounted because it’s in use.

На сервере RD Session Host профиль пользователя в файле VHDX монтируется в каталог C:\users\<username> и выглядит таким образом:

пользователь вошел в windows с UPD профилем

Обратите внимание, что UPD диск привязан к версии Windows Server на RDS хосте. Вы не сможете перенести UPD профиль пользователя с RDS сервера с одной версии Windows Server на другую.

Запись данных в файл vhdx ведется в реальном времени. Т.е. при копировании данных в профиль пользователя на сервере RDS, размер vhdx файла на общем хранилище увеличивается сразу.

Если в Windows уже есть каталог с профилем пользователя, каталог со старым профилем переименовывается в формат <username>-BACKUP-<number>.

VHDX диск монтируется при старте сессии пользователя на VDI или RDS сервере. Каждый UPD профиль монтируется в каталог C:\Users. Список смонтированных VHDX дисков с профилями отображается в консоли Disk Management.

В какую папку смонтирован профиль пользователя UPD

Как расширить/сжать диск User Profile Disk с помощью PowerShell?

Вы можете расширить виртуальный vhdx диск с UPD профилем конкретного пользователя с помощью PowerShell командлета Resize-VirtualDisk из модуля Hyper-V (на компьютере должны быть установлены компоненты управления Hyper-V: Enable-WindowsOptionalFeature -Online –FeatureName Microsoft-Hyper-V-Management-Clients )

Net use U: \\srv01\RDSProfiles
Resize-VHD -Path u:\UVHD-<SID>.vhdx -SizeBytes 30GB
Net use U: /delete

Теперь нужно расширить раздел из графического интерфейса консоли Управления дисками (Disk Manager). Действие –> Подключить виртуальный жесткий диск -> Расширить том.

расширить диск User Profile Disk

Либо воспользуйтесь таким PowesShell скриптом:
<#
.Synopsis
This script extend size of VHDX file and resize the disk partition to Max
#>
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[alias("Path")]
[string]$vhdxFile,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[alias("Size")]
[int64]$vhdxNewSize
)
begin{
try {
Mount-VHD -Path $vhdxFile -ErrorAction Stop
}
catch {
Write-Error "File $vhdxFile is busy"
Break
}
$vhdx = Get-VHD -Path $vhdxFile
if ($vhdx.Size -ge $vhdxNewSize){
Write-Warning "File $vhdxFile already have this size!"
$vhdx | Dismount-VHD
Break
}
}
process{
Dismount-VHD -Path $vhdxFile
Resize-VHD -Path $vhdxFile -SizeBytes $vhdxNewSize
$vhdxxpart = Mount-VHD -Path $vhdxFile -NoDriveLetter -Passthru | Get-Disk | Get-Partition
$partsize = $vhdxxpart | Get-PartitionSupportedSize
$vhdxxpart | Resize-Partition -Size $partsize.SizeMax
}
end{
Dismount-VHD -Path $vhdxFile
}

Обратите внимание, что нельзя расширить UPD диск пользователя с активной RDS сессией.

Чтобы уменьшить размер файла UPD (при условии, что вы удалили данные пользователя внутри vhdx файла и размер файлов на диске меньше выделенного ему размера) можно воспользоваться командами:

resize-VHD \\srv01\RDSProfiles\UVHD-<SID>.vhdx –ToMinimumSize

А затем:

Optimize-vhd -path \\srv01\RDSProfiles\UVHD-<SID>.vhdx -mode full

Временный профиль при использовании User Profile Disk в RDS

Одной из частых проблем, с которых вы можете столкнуться при использовании RDS – периодическое появление временных профилей пользователей.

We can’t sign in to your account.
You’ve have been signed in with a temporary profile.
You can’t access your files, and files created in this profile will be deleted when you sign out. To fix this, sigh out and try signing later.

Вы вошли в Windows Server с временным профилем

При этом для пользователя создается временный профиль:

Event ID 1511
Source: User Profile Service
Windows cannot find the local profile and is logging you on with a temporary profile. Changes you make to this profile will be lost when you log off.

Чаще всего это связано с тем, что в предыдущей сессии VHDX файл пользователя не был освобожден. Вы можете найти RDSH хост, на котором сейчас подключен VHDX диск пользователя. Вы можете использовать такой PowerShell скрипт (запускается на сервере с ролью RD Connection Broker)

$UserToFind = "a.novak"
$User = $env:USERDOMAIN + '\' + $UserToFind
$RDCollection = Get-RDSessionCollection | where {$_.ResourceType -eq 'Remote Desktop'}
$RDHosts = Get-RDSessionHost -CollectionName $RDCollection.CollectionName | select SessionHost
$Array = Invoke-Command -ComputerName $RDHosts.SessionHost -ScriptBlock { Get-Disk | select Location,DiskNumber | where {$_.Location -notmatch "Integrated"} }
foreach ($VHD in $Array){
$DiskID = (Get-Item $VHD.Location).Name.Substring(5).Split(".")[0]
$objSID = New-Object System.Security.Principal.SecurityIdentifier ($DiskID)
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
if ($objUser.Value -eq $User){
$result = "$($objUser.Value) disk number $($VHD.DiskNumber) on $($VHD.PSComputername)"
}else{
$result = "$($User) - no active RSH sessions were found."
}
}
$result

PowerShell: найти RDSH хост, где подключен UPD профиль пользователя

Можно удаленно отмонтировать UPD диск командой:

Invoke-Command -ComputerName $VHD.PSComputername -ScriptBlock { Dismount-VHD -DiskNumber $VHD.DiskNumber }

Чтобы уменьшить количество проблем с временными профилями на RDS, рекомендуем настроить таймауты для RDS сессий пользователей (установите отключение через 2-4 часа для неактивных сессий). Также вы можете включить параметр GPO, который запрещает создание временных профилей: Computer Configuration -> Administrative Templates -> System -> User profiles, включите параметр Do not log users on with temporary profiles.

GPO: не создавать временные профили для пользователей

После освобождении VHDX диска администратору нужно вручную удалить временный профиль пользователя:

  1. Удалите ветки с SID пользователя в разделе реестра
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
    . В этом примере есть две ветки, одна из которых с суффиксом .bak); очистка временных профилей в реестре Windows NT\CurrentVersion\ProfileList
  2. Удалите TEMP папку пользователя из каталога
    C:\Users
    .

    Подробнее об удалении профилей пользователей в Windows в статье по ссылке.

В этой статье мы рассмотрели, как настроить профили User Profile Disks в RDS на Windows Server. Настройка UPD намного проще чем процесс настройки перемещаемых профилей и перенаправляемых папок. Диски привязаны к коллекции RDS и не могут повредиться при попытке совместного использования профиля несколькими терминальными серверами (в отличии от обычных профилей). Диски профилей пользователей могут храниться на SMB шарах, CSV, SOFS, в SAN или на локальных дисках.

RDS User Profile Disks are an alternative to roaming profiles and folder redirection in the RDS scenarios.

As part of our Server Management Services, we assist our customers to setup User Profile Disk in Windows.

Today, let’s see some of its benefits and how our Support Engineers configure it.

User Profile Disks (UPD)

User Profile Disks (UPD) is a new feature of Remote Desktop Services in Windows Server 2012.

The whole point of UPD is to store user and apps data in a separate VHDX disk on the network shared folder. This virtual disk is mounted to the user session as soon as we sign in to the RDS server, and unmounted when we log out.

Let us now focus on some key suggestions from our Support Engineers.

Benefits of RDS User Profile Disks

  • Configuration and deployment is simple
  • Maintain on pooled virtual desktops that get rolled back after logoff
  • Less logon and logoff time
  • Specific to the collection, cannot use on multiple computers simultaneously
  • Administrators can have granular control of exactly which locations get saved to the virtual hard disk (VHDX)
  • Stored on Server Message Block (SMB) shares, cluster shared volumes, SANs, or local storage.

Points to note before we configure RDS User Profile Disks

  • User profile disks are for a single collection.

A user connecting to two different collections will have two separate profiles;

  • Properties are set automatically upon creation and contain all profile data and registry settings by default.

These properties can be defined prior to creation or after in the ‘Session Collection’ properties from ‘Server Manager’;

  • A form of central file share is required as the UNC path of this share is to provide in the wizard during initial configuration.

One major benefit of these file shares is that when more RDS hosts are added to support the collection, those hosts automatically add to the ACL of the share, not requiring an administrator to take any action in modifying security permissions;

  • Single session.

If a user logs into one RDS host, they cannot connect to another and they cannot have more than one session active on a single host;

  • User Profile Disks are created using a naming scheme that corresponds to a user’s GUID and makes identifying the UPD associated with a user a very risky task.

Best practices when working with RDS User Profile Disks

Given that a user will have a UPD respective to each collection, each will therefore require respective file shares. It’s advisable to name each file share according to the collection with which it associates.

Leverage the benefits of new file server technology in Server 2012 R2 – Scale Out File Server (SOFS)
+ SOFS differs from clustered file servers in that all file shares on all nodes are always active instead of being active on one node at any given time – active/active instead of active/passive

Configuring RDS User Profile Disks on Windows

First of all, it is necessary to create a shared folder on any corporate file server to store user profiles as VHDX disk.

For example, the path to our folder will be: \\rdvh1\DemoLabOficeApp.

Servers which are a part of RDS collection should have full access permission to access this shared folder.

In a single RDS collection, there can exist only one VHDX profile file for one user. If a user connects to the resources from different collections, we should create a separate profile disk for each.

We can configure RDS User Profile Disks in the collection settings of Remote Desktop Services. We can enable this mode while creating a new collection.

In our example, the collection already exists, so in the Server Manager console, we select this collection and in the upper left corner click Tasks -> Edit Properties.

Here. in User Profile Disks section we ‘Enable’ user profile disks, specify the path to the previous shared folder (\\rdvh1\DemoLabOficeApps) and a maximum profile disk size. Then we save the changes.

Once done, we make sure to change NTFS permissions for Profile Disks folder. In our case, the collection consists of one RDSH01 server, which has full control permission.

Hence, a full Control permissions is given to the RDSH01 server on the shared folder level.

When we add new RD Session Host servers to the RDS collection, the wizard automatically changes the folder permissions and gives access to the new servers.

It is very convenient, since when scaling a terminal farm we do not need to remember to set permissions for the profile folder.

[Need help to configure RDS User Profile Disks on Windows? We are available 24*7]

UPD: User profile as VHDX file

First, we have to go to the network shared folder with user profiles. There is a UVHD-template.vhdx file. This file is the user profile disk template.

When a user logs on to the RDS server for the first time, this template copies and renames as a VHDX file, with user SID in its name.

To match an UPD file name with the user name, we must use a separate script.

For example, we can convert the SID to an account name by using the Get-ADUser cmdlet:

Get-ADUser -Identity S-1-5-21-32549751-3956249758-2943215497-23733695
  • What does User profile disk contain?

Right-click the VHDX file and select Mount. The UPD disk can only be used in one session on one RDS host (exclusive access). We cannot mount an UPD VHDX disk if the user is currently using it on the RDS server.

Configure RDS User Profile Disks on Windows

As we can see, the VHDX disk contains a set of folders and files of a standard user profile. At logon, a user gets completely transparent access to the data in the profile.

On the side of RD Session Host server, a .vhdx user’s file is mounted to the C:\users\<username> and looks like this:

RDS User Profile Disks

Note that the UPD drive is bound to the RDS server Windows OS version. We cannot transfer (use) an UPD user profile from an RDS server from one version of Windows Server to another.

Data is written to the vhdx file in real time. When copying data to a user profile on an RDS server, the size of the vhdx file on the shared storage increments immediately.

If the user profile folder already exists in the system, the folder with an old profile renames to the <username>-BACKUP-<number>.

The VHDX disk is mounted when the user session starts on a VDI or RDS server. A list of connected UPD disks with profiles can be listed using the mountvol utility.

  • The three options:

By default, a User Profile Disk contains all the user profile contents. However, we can exclude certain folders from the list of synchronized directories in the RDS collection settings.

Thus, all the changes made during the user’s terminal session to the folders in the list of excluded directories are not saved into the VHDX disk on the shared folder.

User Profile Disks

The second option allows us to save only specific directories in the UPD profile.

RDS User Profile Disks

If necessary, the last option allows us to implement the scenarios for saving the settings of the Start Screen, in appsfolder.itemdata-ms file.

In this example, we have only added the path to \AppData\Local\Microsoft\Windows folder as an additional path to be saved in the UPD.

RDS

[Stuck with User Profile Disks? We are here for you]

Resizing RDS User Profile Disks Using PowerShell

We can extend the virtual vhdx drive with the user’s UPD profile using the PowerShell cmdlet Resize-VirtualDisk from the Hyper-V module.

Net use U: \\rdvh1\DemoLabOficeApps
Resize-VHD -Path u:\UVHD-<SID>.vhdx -SizeBytes 40GB
Net use U: /delete

If we want to run the Resize-VHD cmdlet from a desktop with Windows 10, we must install the feature: Hyper-V -> Hyper-V Platform -> Hyper-V Services.

Now we need to extend the volume from the GUI of the Disk Management console (Action -> Attach VHD -> Extend volume).

Or we use the following PowerShell script to automatically extend the vhdx file to the maximum available size:

<#
.Synopsis
This script extend size of VHDX file and resize the disk partition to Max
#>
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[alias(“Path”)]
[string]$vhdxFile,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[alias(“Size”)]
[int64]$vhdxNewSize
)
begin{
try {
Mount-VHD -Path $vhdxFile -ErrorAction Stop
}
catch {
Write-Error “File $vhdxFile is busy”
Break
}
$vhdx = Get-VHD -Path $vhdxFile
if ($vhdx.Size -ge $vhdxNewSize){
Write-Warning “File $vhdxFile already have this size!”
$vhdx | Dismount-VHD
Break
}
}
process{
Dismount-VHD -Path $vhdxFile
Resize-VHD -Path $vhdxFile -SizeBytes $vhdxNewSize
$vhdxxpart = Mount-VHD -Path $vhdxFile -NoDriveLetter -Passthru | Get-Disk | Get-Partition
$partsize = $vhdxxpart | Get-PartitionSupportedSize
$vhdxxpart | Resize-Partition -Size $partsize.SizeMax
}
end{
Dismount-VHD -Path $vhdxFile
}

Note that we cannot extend the user’s UPD disk with an active RDS session.

To reduce the size of the UPD file, we can use the commands:

resize-VHD \\rdvh\DemoLabOficeApps\UVHD-<SID>.vhdx –ToMinimumSize

And then:

Optimize-vhd -path \\rdvh1\DemoLabOficeApps\UVHD-<SID>.vhdx -mode full

So, we have discussed the major peculiarities of User Profile Disks in RDS/VDI solutions running Windows Server 2016 and 2012 R2.

UPD configuration is much easier than the configuration of roaming profiles or redirected folders. The disks connects to the RDS collection and cannot damage while using the shared profile by several servers.

We can store the User Profile Disks in SMB shares, CSV, SOFS, SAN or on the local disks.

If we are planning to store UPD profiles on DFS servers, we must install Windows Server 2012 R2. If we are using previous versions of Windows Server, we will get an error:

Unable to enable user disks on rVHDShare. Could not create template VHD. Error Message: The network location “\\bobcares.com\namesp

Also it is desirable to use the version SMB 3.02 on the file server side (Windows Server 2012 R2) or higher.

Anyway, since User Profile Disks is a relatively new technology, prior to mass UPD implementations, we recommend to test their work and possible problems in a test environment.

[Need assistance to configure RDS User Profile Disks? We are happy to help.]

Conclusion

In short, RDS User Profile Disks is an alternative to roaming profiles and folder redirection in the RDS scenarios. Today, we saw how our Support Engineers configure the same.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

User Profile Disk (UPD) allows you to store the profile of each Remote Desktop Services user (%USERPROFILE%) in a separate VHDX (virtual disk) file. Such a profile disk is connected when the user logs on to Windows and will be disconnected when the user logs out (with the changes to the profile being saved). You can store user profile disks on an external file share so that a user can access their personal environment (profiles) when they login to any server in the RDS farm. UPDs are an alternative to roaming profile or folder redirection technologies in RDS terminal solutions.

In this article, we’ll describe how to configure and manage User Profile Disks on hosts with the Remote Desktop Services role running on Windows Server 2022, 2019, 2016, or 2012R2.

Contents:

  • Enable User Profile Disks on Windows Server RDS
  • User Profile Disks in VHDX Files on RDS
  • How to Expand/Reduce User Profile Disk with PowerShell?
  • Temporary Profile Issue When Using User Profile Disks on RDS

Enable User Profile Disks on Windows Server RDS

Create a shared network folder to store the UPD profile files. This folder must be located on a file server outside the RDS farm. To ensure the high availability of UPD profiles, we recommend that you place the network folder on a cluster. The path to such a directory looks like this in our example: \\fs01\RDSProfiles .

Create a security group in AD and add all the hosts in your RDS collection to it. You can create a group using the ADUC graphical console or using cmdlets from the Active Directory for Windows PowerShell module:

New-ADGroup munRDSHCollection1 -path "OU=Groups,OU=MUN,DC=woshub,DC=loc" -GroupScope Domain -PassThru –Verbose
Add-AdGroupMember -Identity munRDSHCollection1 -Members munrds1$, munrds2$, munrds3$

To add computers to an AD group, you must add $ to the end of the computer name (this is part of the SAMAccountName attribute).

Now grant Full Control permissions on the \\fs01\RDSProfiles folder for the munRDSHCollection1 group.

Configure share permissions for User Profile Disks

You can enable User Profile Disks in the Remote Desktop Collection settings when you create it. If the collection already exists, find it in the Server Manager console and select Tasks-> Edit Properties in the upper right corner.

User Profile Disks mode can be enabled and configured in the collection settings of Remote Desktop Services. This mode can be enabled when creating a new collection, or you can return to it later.

Edit RDS collection

Then go to the User Profile Disks tab. Check the option Enable user profile disks, specify the path to the previously created shared folder (\\fs01\RDSProfiles), and set a maximum profile disk size (let it be 7 GB). Save the changes.

Enable user profile disks in RDS collection

It is possible to use a DFS namespace to store the UPD profiles of a DFS server, but this configuration is not officially supported. DFS hosts must be running Windows Server 2012 R2 or later. If you are using earlier versions of Windows Server, you will receive an error:

Unable to enable user disks on rVHDShare. Could not create template VHD.  Error Message: The network location "\\woshub.com\namespace\UserProfileDisk" is not available.

You can check if UPD is enabled for the RDS collection and get the path to the directory where the profiles are stored with the PowerShell command:

Get-RDSessionCollectionConfiguration -CollectionName munCorpApp1 –UserProfileDisk

Get-RDSessionCollectionConfiguration UserProfileDisk

Tip. In a single RDS collection, there can exist only one VHDX profile file for one user. If a user connects to the resources from two different collections, a separate profile disk will be created for each of them.

By default, a User Profile Disk contains all the user profile contents. You can exclude certain folders from the list of synchronized directories or specify that only certain folders should be saved. Thus, any changes made to the folders in the list of excluded directories during the user’s terminal session will not be saved to the VHDX disk in the shared folder. There are two options available:

  • Store all user settings and data on the user profile disk
  • Store only the following folders in the user profile disk

Exclude/include specific folder to a user profile disk in RDS collection

If you are using RDS with UPD on Windows Server 2019/2016, over time you may experience RDS host performance degradation and a black screen when logging in via RDP. We recommend you immediately enable the DeleteUserAppContainersOnLogoff registry option on all RDS hosts.

New-ItemProperty -Path “HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy” -Type DWord -Path -Name DeleteUserAppContainersOnLogoff -Value 1

User Profile Disks in VHDX Files on RDS

After you have changed the collection settings and enabled UPD, a file called UVHD-template.vhdx will be created in the target UPD folder.

This file is the template for the user’s profile disk. When a user logs on to the RDS server for the first time, this template is copied and renamed as a VHDX file with the user’s SID in the name. For each user, a separate VHDX file is created.

Hint. For detailed logs about using UPD to log on to the server, see Event Viewer -> Application (with the User Profile Service source) and Applications and Services Logs -> -Microsoft -> Windows -> User Profile Service -> Operational.

UVHD-template.vhdx file on RDS

You can match the UPD file name with the owner user. For example, you can manually convert the SID to a user account name using the Get-ADUser cmdlet:

Get-ADUser -Identity S-1-5-21-32549751-3956249758-2943215497-23733695

Or use the ShowUPDFolderDetails.ps1 script, which displays the names of UPD files in a specified folder and their owners:

$UPDShare = "\\fs01\RDSProfiles"
$UserProfiles = @()
$fc = new-object -com scripting.filesystemobject
$folder = $fc.getfolder($UPDShare)
"Username,SiD" >> export.csv
foreach ($i in $folder.files)
{
$sid = $i.Name
$sid = $sid.Substring(5,$sid.Length-10)
if ($sid -ne "template")
{
$securityidentifier = new-object security.principal.securityidentifier $sid
$user = ( $securityidentifier.translate( [security.principal.ntaccount] ) )
$UserProfile = New-Object PSObject -Property @{
UserName = $user
UPDFile=$i.Name
}
$UserProfiles += $UserProfile
}
}
$UserProfiles| select UserName, UPDFile

Find out which User Profile Disk maps to which Domain User account with PowerShell

Since the UPD profile is a regular virtual disk file in VHDX format, you can mount it and view its contents from any Windows host. Right-click the file and select Mount.

Mount UPD vhdx file in Windows

As you can see, the VHDX disk contains a set of folders and files of a standard user profile.

user profile disk folders

On the RD Session Host, the user profile in the VHDX file is mounted to the C:\users\<username> and looks like this:

Check user profile disks mounted in C:\users folder

The UPD profile is mounted in exclusive mode. This means that if a user profile is currently connected to the user’s RDS session or manually mounted, you will not be able to open it with an error: The file couldn’t be mounted because it’s in use.

The User Profile Disks from an RDS server cannot migrate between versions of Windows Server.

Data is written to the VHDX file in real time. This means that when data is copied to a user profile on an RDS server, the size of the vhdx file on the shared storage is increased immediately.

If the user profile folder already exists in Windows, the folder with an old profile is renamed to the <username>-BACKUP-<number>.

A VHDX disk is mounted when a user logs on to a VDI or RDS host. Each UPD profile is mounted to the C:\Users directory. The list of mounted VHDX disks and mount points of the user profiles appears in Disk Management.

Disk Management - list user profile disk and mount points

How to Expand/Reduce User Profile Disk with PowerShell?

You can expand or shrink a virtual VHDX disk image with a specific user’s UPD profile using the Resize-VirtualDisk PowerShell cmdlet from the Hyper-V module (Hyper-V management tools must be installed on a computer: Enable-WindowsOptionalFeature -Online –FeatureName Microsoft-Hyper-V-Management-Clients):

Net use U: \\fs01\RDSProfiles
Resize-VHD -Path u:\UVHD-<SID>.vhdx -SizeBytes 40GB
Net use U: /delete

Now you need to increase the volume size from the Disk Management console GUI (Action -> Attach VHD -> Extend volume).

Extend volume on the vhdx disk

Or use the following PowerShell script to automatically extend the VHDX file to the maximum available size:

<#
.Synopsis
This script extend size of VHDX file and resize the disk partition to Max
#>
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[alias("Path")]
[string]$vhdxFile,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[alias("Size")]
[int64]$vhdxNewSize
)
begin{
try {
Mount-VHD -Path $vhdxFile -ErrorAction Stop
}
catch {
Write-Error "File $vhdxFile is busy"
Break
}
$vhdx = Get-VHD -Path $vhdxFile
if ($vhdx.Size -ge $vhdxNewSize){
Write-Warning "File $vhdxFile already have this size!"
$vhdx | Dismount-VHD
Break
}
}
process{
Dismount-VHD -Path $vhdxFile
Resize-VHD -Path $vhdxFile -SizeBytes $vhdxNewSize
$vhdxxpart = Mount-VHD -Path $vhdxFile -NoDriveLetter -Passthru | Get-Disk | Get-Partition
$partsize = $vhdxxpart | Get-PartitionSupportedSize
$vhdxxpart | Resize-Partition -Size $partsize.SizeMax
}
end{
Dismount-VHD -Path $vhdxFile
}

Note that you can’t expand the UPD disk of a user with an active RDS session.

To reduce the size of the UPD file (assuming that you deleted the user’s data inside the vhdx file and the data size on the disk is less than the size assigned to it), you can use the commands:

Resize-VHD \\fs01\RDSProfiles\UVHD-<SID>.vhdx –ToMinimumSize

And then optimize the allocation of space in the file:

Optimize-vhd -path \\fs01\RDSProfiles\UVHD-<SID>.vhdx -mode full

Temporary Profile Issue When Using User Profile Disks on RDS

Temporary user profiles are one of the most common problems you may encounter when using roaming profiles or user profile disks on RDS:

We can’t sign in to your account.
You’ve have been signed in with a temporary profile.
You can’t access your files, and files created in this profile will be deleted when you sign out. To fix this, sigh out and try signing later.

RDS: You’ve have been signed in with a temporary profile.

A temporary profile is created for the user in this case:
Event ID 1511
Source: User Profile Service

A temporary profile is created for the user because Windows cannot find the local profile. Changes you make to this profile will be lost when you log off.

Most often, this is because the user’s VHDX file was not closed in the previous session. Use the following PowerShell to locate the RDSH host on which the user’s VHDX drive is mounted (run the script on the host with the RD Connection Broker role):

$UserToFind = "a.smith"
$User = $env:USERDOMAIN + '\' + $UserToFind
$RDCollection = Get-RDSessionCollection | where {$_.ResourceType -eq 'Remote Desktop'}
$RDHosts = Get-RDSessionHost -CollectionName $RDCollection.CollectionName | select SessionHost
$Array = Invoke-Command -ComputerName $RDHosts.SessionHost -ScriptBlock { Get-Disk | select Location,DiskNumber | where {$_.Location -notmatch "Integrated"} }
foreach ($VHD in $Array){
$DiskID = (Get-Item $VHD.Location).Name.Substring(5).Split(".")[0]
$objSID = New-Object System.Security.Principal.SecurityIdentifier ($DiskID)
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
if ($objUser.Value -eq $User){
$result = "$($objUser.Value) disk number $($VHD.DiskNumber) on $($VHD.PSComputername)"
}else{
$result = "$($User) - no active RSH sessions were found."
}
}
$result

PowerShell script: find the RDS host where UPD (VHDX is mounted

You can unmount the UPD virtual drive remotely with the command:

Invoke-Command -ComputerName $VHD.PSComputername -ScriptBlock { Dismount-VHD -DiskNumber $VHD.DiskNumber }

To reduce problems with temporary profiles on RDS, it is a good idea to configure timeouts for RDS user sessions. Set idle/disconnected sessions to terminate after 2 to 4 hours. You can also enable the GPO setting that prevents creating temporary profiles: Computer Configuration -> Administrative Templates -> System -> User profiles, enable the option Do not log users on with temporary profiles.

GPO: Do not log users on with temporary profiles

This policy setting may intermittently cause the “The User Profile Service failed the sign-in, user profile cannot be loaded” if the user profiles folder is unavailable.

The administrator must manually delete the temporary user profile on the RDS host after releasing the VHDX disk:

  • Delete the subkeys with the user SID under the following registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList. In this example, there are two subkeys, one of which ends with .bak (delete them both); delete temp profile from registry
  • Remove the user’s TEMP profile folder from the C:\Users directory.

The User Profile Disk technology, which was introduced nearly ten years ago (in Windows Server 2012), has a number of drawbacks. Microsoft currently recommends using the newer FSLogix containers to store RDS user profiles.

So, we have looked at how to configure User Profile Disks in RDS/VDI environment on a Windows Server. Configuring UPDs is much easier than configuring roaming profiles or redirected folders. User Profile Disks are bound to an RDS collection and cannot be corrupted when a user profile is shared between multiple terminal servers (unlike standard user profile folders). The User Profile Disks can be stored on SMB shares, CSV, SOFS, SAN, or local disks.

When you create a collection on an RDS infrastructure to publish RemoteApp desktops or programs, you’ve probably noticed that you can enable user profile disks

These user profile disks allow your users to back up data from the desktops and/or RemoteApp programs published from your RDS server and retrieve them later on their next connections.
Because RDS collections can group multiple session hosts, it’s important that their data be kept in the same place and not on the session host server your user arrives at.

In addition, to avoid conflicts and various problems, it’s recommended that you store these user profile disks in different network shares or folders for each collection (1 network share or 1 folder per collection).

To enable, disable, or change the settings for these user profile disks, select the desired collection, and then click : Tasks -> Edit properties.

Go to the «User Profile Disks» section and check the «Enable user profile disks» box to enable them for this collection.
Create a shared folder on a file server (preferably highly available), then specify its network path in the «Location» box.

For more information, see our tutorial : Deploy a RDS infrastructure (session-based desktops)

As you can see, you can choose to :

  • store all user settings and data, then exclude specific folders
  • store only specific folders in the user’s profile disk

This choice will essentially depend on the needs of your user and what they can do or not on this desktop or these RemoteApp programs.

For example, for excluded folders, you can exclude the user’s temporary folder and/or other folders containing temporary files related to RemoteApp programs published in this collection.

If your user is not supposed to back up files from published RemoteApp programs, it may be interesting to choose the option «Store only the following folders on the user profile disk» and uncheck the boxes displayed.

Note that it’s also possible to delete temporary folders when closing the user’s session by going to the «Session» section, then checking the «Delete temporary folders on exit» box.

Have an issue you can’t solve? I offer consulting engagements and can be reached here: consulting[а𝐭]amorales[․]org

Last Updated 2020-01-03




After months of testing I recommend deploying FSLogix Profile Containers instead of User Profile Disks. You can find my guide here. Some of the items below apply to FSL Profile Containers. 


User Profile Disks (UPDs) are great for load balanced RDS farms since it allows users to seamlessly roam from server to server. The goal of this article will be to configure the RDS and file servers in a way that maximizes performance and reduces the likelihood of UPD disconnects.


I’ll keep this updated any time I find new improvements.


Use FSLogix
Before you even consider deploying UPDs you need to be aware of this limitation. On Server 2012 and 2016 (Server 2019 does not have this issue, but it doesn’t support Office) the Windows Search index is machine wide. This means that when a UPD is disconnected the user’s index data is deleted. The result is that the next time the user logs into the RDS and opens Outlook their search index will need to rebuild. This will become a major issue when you have 5+ users on a server and the index throttles itself. You could disable the index back off, but it will lead to performance issues and it won’t actually fix the issue.


The solution is to configure FSLogix Office 365 containers. What they have done is create their own «UPD» that stores all the user’s Outlook and index data. The next time the user signs into the server their index will load instantly.


Location of Servers
In order to reduce latency and the likelihood of a UPD disconnect; the server hosting the UPD share should be on the same VMware host as the RDS servers. This might not always be possible based on your configuration, but it is ideal since it keeps all the network traffic within VMware.


Use ReFS for the UPD drive
Using ReFS as the file system of the drive that will host the UPDs will improve VHDX performance. This will be evident when creating UPDs(first login) and when they need to expand. More info here.


Set all your servers to High Performance
Make sure that all your servers are set to a High Performance power plan. This will make sure that none of the power settings lead to disconnections.


Compact your UPDs
UPDs are dynamic VHDX files that can expand up to 20GB by default. The UPD automatically expands any time the user adds data to it, but it never compacts once data is removed. As a result, you may end up with a ton of blank used space.


The script below can be configured as a scheduled task on your file server. It will go through your UPD share and compact any VHDX files that are not in use.


Compact-UPDs.ps1


Disable Share Caching
Disabling share caching can prevent some rare situations where the UPD fails to dismount from the RDS server. It also has no negative effects since there is no need to cache the UPD files.


Go to the Caching Settings of the profile disk share and select «No files or programs from the shared folder are available offline»



Restart your RDS servers after the File Server
If you have scheduled restarts, make sure that the RDS servers restart after the File Server. If a user left their session open on the RDS and the file server restarts their session will get stuck. Restarting the RDS servers after the file server ensures that all sessions are cleared.


Delete Inactive Printer Ports
Don’t do this on 2019 servers! It will break redirection.

There is an issue where printer redirection ports don’t get cleared out when users log out. This can result in long login times. This article says that it only affects 2008 R2, but I have seen 2012 and 2016 servers with thousands of unused ports. Thankfully there is an application that can delete them. 

  1. Download InactiveTSPort from the archive https://archive.codeplex.com/?p=inactivetsport
  2. go to the releases/1 folder and rename the file «46d7de43-82ec-4984-b550-6580a82ee735» to «DeleteInactivePortSilently.exe«
  3. Create a scheduled task that runs the exe every few days

Delete bad folders under the Users Folder
Have you ever looked at your C:\Users folder and seen a ton of .BACKUP-0 folders? I have a possible cause of the issue on the next point. These .BACKUP-## folders can lead to some issues like Outlook not being able to find the OST of a user when launched.


Set the script below as a scheduled task that runs every morning. The script uses DelProf2 to delete all the folders under the C:\Users directory. This will only delete profiles of users that are not logged in. I exclude the UvhdCleanupBin folder since its purpose seems to be a bit of a mystery.


Create scheduled Task Remove-UPDOldProfilesScheduledTask.ps1


Remove-LocalUPDProfiles.ps1

Log users out of the Server before restarting it

This is a bit of speculation, but I believe that the .BACKUP-## folder issue is caused by restarting the server while UPDs are attached. If you restart servers on a schedule, then it might be worth creating a script that logs all users out of the RDS before it is restarted.

Delete old firewall rules at logoff

Every time a user logs into an RDS server several Firewall rules are created. These rules are never deleted and over time you will have thousands of unnecessary rules on all your servers. These rules can lead to performance issues and crashing. Also, the rules will show up even if you have the firewall disabled.

Install KB4467684 and create a GPO that creates the following reg key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy

DeleteUserAppContainersOnLogoff (DWORD)

Value: 1

The next time a user logs in and back out of a server the rules will be cleared. More info here.

Redirect Common User Folders

Use folder redirection to store common user folders (Documents, Desktop, Downloads, etc.). This will allow you minimize the size of UPDs and it will make management easier. For instance, if you upgrade from Server 2012 to 2016 you will only need to worry about user settings and not their documents. 

AV Exclusions

Make sure to exclude VHDX files from your AV, and make sure that they actually show up on the client’s exclude list. In my case simply excluding *.vhdx files from ESET did not do the trick. I had to create the exclusions below.

\\SERVER\*.vhdx (File Server)

\\EXAMPLE.COM\*.VHDX (DFS namespace) (you only need this if you’re deploying FSLogix)

L:\*.vhdx (Local drive on the file server)

Storing data on the UPD

The RDS session properties give you two choices on how to store data. «Store all user settings and data on the user profile disk» and «store only the following folders on the user profile disk». I opt for «Store all user settings and data on the user profile disk» this ensures that none of the user’s data is lost.

If i need to exude something I use the exclude list.

Start Menu not working?

Excluding the paths below and creating the reg key might help with the issue. See thread with more info here and here.

Exclude:

AppData\Local\Packages (Folder)

AppData\Local\Microsoft\Windows\Usrclass.dat (File) (This is supposed to cause users to lose their default Apps, but I have not seen that occur[see here for other things that might be lost])

After some testing I have confirmed that the notification area icon settings will not persist across sessions if Usrclass.dat is excluded. All non system icons will be hidden again the next time a user signs in.  

Reg key:

HKCU\Software\Microsoft\Windows\CurrentVersion\ImmersiveShell\StateStore\ResetCache

DWORD

1

Have any ideas or improvements? Share them in the comments. Also, let me know if you think I got anything wrong.

  • User configuration policies administrative templates windows components
  • User password reset windows password
  • User oobe broker что это за процесс windows 10
  • Usb3 driver for windows 10
  • User logon name pre windows 2000 что это