Перейти к содержимому

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

Скрипт ищет пользователей у которых не с монтировался профил fslogix и переиеновать диски User Disk по стандарту. User disc появился из за миграции профилей из UDP windows

# === Настройки ===
$collectionName = "Fxlogixs"
$connectionBroker = "HWRDCB.adminbd.ru"

# === 1. Получаем все сессии из коллекции ===
Write-Host "Получение сессий из коллекции '$collectionName' через брокер '$connectionBroker'..." -ForegroundColor Cyan
try {
    $sessions = Get-RDUserSession -CollectionName $collectionName -ConnectionBroker $connectionBroker -ErrorAction Stop
} catch {
    Write-Error "❌ Ошибка при получении сессий: $($_.Exception.Message)"
    exit 1
}

if (-not $sessions) {
    Write-Host "ℹ️ Нет сессий в коллекции." -ForegroundColor Green
    exit 0
}

# === 2. Фильтруем: только сессии с заполненным HostServer ===
$validSessions = $sessions | Where-Object {
    $_.HostServer -and $_.HostServer.Trim() -ne ''
}

Write-Host "Всего сессий: $($sessions.Count)" -ForegroundColor Gray
Write-Host "Валидных (с HostServer): $($validSessions.Count)" -ForegroundColor Cyan

if (-not $validSessions) {
    Write-Host "❌ Нет валидных сессий для проверки." -ForegroundColor Red
    exit 0
}

# === 3. Группируем сессии по хосту ===
$sessionsByHost = $validSessions | Group-Object HostServer
$problemUsers = @()

# === 4. Проверяем каждый хост: смонтирован ли профиль? ===
foreach ($group in $sessionsByHost) {
    $hostName = $group.Name.Trim()
    $hostSessions = $group.Group

    Write-Host "`n🔍 Проверка хоста: $hostName" -ForegroundColor Yellow

    try {
        $userNamesToCheck = $hostSessions.UserName | ForEach-Object { ($_ -split '\\')[-1] }

        $mountedUsers = Invoke-Command -ComputerName $hostName -ScriptBlock {
            param($expectedNames)

            $mounted = @()
            $volumes = Get-Volume -ErrorAction SilentlyContinue |
                       Where-Object { $_.FileSystemLabel -and $_.FileSystemLabel.StartsWith("Profile-") }

            foreach ($vol in $volumes) {
                $userNameFromLabel = $vol.FileSystemLabel.Substring("Profile-".Length)
                $userNameClean = ($userNameFromLabel -split '\\')[-1].Trim()

                foreach ($exp in $expectedNames) {
                    if ($userNameClean -eq $exp -or $userNameClean.ToLower() -eq $exp.ToLower()) {
                        $mounted += $exp
                        break
                    }
                }
            }
            return $mounted
        } -ArgumentList (,$userNamesToCheck) -ErrorAction Stop

        foreach ($session in $hostSessions) {
            $userName = ($session.UserName -split '\\')[-1]
            if ($userName -notin $mountedUsers) {
                $problemUsers += [PSCustomObject]@{
                    UserName     = $session.UserName
                    SessionHost  = $session.HostServer
                    SessionId    = $session.UnifiedSessionId
                    SessionState = $session.SessionState
                    Status       = "Профиль НЕ смонтирован (том отсутствует)"
                }
                Write-Host "⚠️  $userName — профиль не смонтирован!" -ForegroundColor Red
            } else {
                Write-Host "✅ $userName — профиль смонтирован." -ForegroundColor Green
            }
        }
    } catch {
        Write-Warning "🚫 Не удалось проверить хост '$hostName': $($_.Exception.Message)"
        foreach ($session in $hostSessions) {
            $problemUsers += [PSCustomObject]@{
                UserName     = $session.UserName
                SessionHost  = $session.HostServer
                SessionId    = $session.UnifiedSessionId
                SessionState = $session.SessionState
                Status       = "Ошибка проверки (недоступен хост / WinRM / нет прав)"
            }
        }
    }
}

# === 5. Автоматическое переименование томов "User Disk" на всех хостах ===
Write-Host "`n" + ("=" * 80) -ForegroundColor Cyan
Write-Host "🔧 Этап 2: Поиск и переименование томов 'User Disk'..." -ForegroundColor Cyan
Write-Host ("=" * 80) -ForegroundColor Cyan

$renameResults = @()
$hostsWithDisks = $sessionsByHost | ForEach-Object { $_.Name.Trim() } | Sort-Object -Unique

foreach ($hostName in $hostsWithDisks) {
    Write-Host "`n🛠️  Обработка хоста: $hostName" -ForegroundColor Magenta

    try {
        $results = Invoke-Command -ComputerName $hostName -ScriptBlock {
            $output = @()
            $userDisks = Get-Volume -ErrorAction SilentlyContinue |
                         Where-Object { $_.FileSystemLabel -eq "User Disk" }

            if (-not $userDisks) {
                $output += "ℹ️ Нет томов с меткой 'User Disk'"
                return $output
            }

            foreach ($vol in $userDisks) {
                try {
                    $dirInfo = New-Object System.IO.DirectoryInfo($vol.Path)
                    $acl = $dirInfo.GetAccessControl()

                    $userRule = $acl.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) |
                        Where-Object {
                            ($_.IdentityReference -notlike "NT AUTHORITY\*") -and
                            ($_.IdentityReference -notlike "BUILTIN\*") -and
                            ($_.IdentityReference -notlike "CREATOR OWNER") -and
                            ($_.IdentityReference -notlike "Everyone")
                        } | Select-Object -First 1

                    if (-not $userRule) {
                        $output += "⚠️ ACL пуст для тома $($vol.Path)"
                        continue
                    }

                    $identity = $userRule.IdentityReference.ToString()
                    $username = if ($identity -match '^[^\\]+\\(.+)$') { $matches[1] } else { $identity }
                    $newLabel = "Profile-$username"

                    # Переименовываем
                    $vol | Set-Volume -NewFileSystemLabel $newLabel

                    $output += "✅ Переименован: 'User Disk' → '$newLabel'"
                } catch {
                    $output += "❌ Ошибка на томе $($vol.Path): $($_.Exception.Message)"
                }
            }
            return $output
        } -ErrorAction Stop

        $renameResults += [PSCustomObject]@{
            Host    = $hostName
            Details = $results -join "`n"
        }

        $results | ForEach-Object { Write-Host "   $_" -ForegroundColor Gray }
    } catch {
        Write-Warning "🚫 Не удалось обработать тома на хосте '$hostName': $($_.Exception.Message)"
        $renameResults += [PSCustomObject]@{
            Host    = $hostName
            Details = "Ошибка подключения или выполнения"
        }
    }
}

# === 6. Итоговый отчёт ===
Write-Host "`n" + ("=" * 90) -ForegroundColor Gray

if ($problemUsers) {
    Write-Host "❌ НАЙДЕНЫ ПРОБЛЕМЫ: активная сессия есть, но FSLogix-том не смонтирован" -ForegroundColor Red
    Write-Host ("=" * 90) -ForegroundColor Gray
    $problemUsers | Format-Table -AutoSize
} else {
    Write-Host "✅ У всех пользователей с сессией FSLogix-профиль смонтирован корректно." -ForegroundColor Green
}

Write-Host "`n" + ("=" * 80) -ForegroundColor Cyan
Write-Host "📄 Итог переименования 'User Disk':" -ForegroundColor Cyan
Write-Host ("=" * 80) -ForegroundColor Cyan

$renameResults | ForEach-Object {
    Write-Host "🖥️  $($_.Host)" -ForegroundColor Yellow
    Write-Host "   $($_.Details)" -ForegroundColor Gray
    Write-Host ""
}

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

Similar Posts:

Добавить комментарий

Яндекс.Метрика