Created
July 31, 2024 08:22
-
-
Save Semdevmaster/e172ae5e7040c96f10ad58b22aa141fe to your computer and use it in GitHub Desktop.
Удаление RPD сессий пользователей с исключениями по имени пользователя
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-FilteredSessionIDs { | |
param ( | |
[string]$ComputerName = "$env:COMPUTERNAME", | |
[string]$ExcludedUsers = "" | |
) | |
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 | |
$sessionsOutput = quser /server:$ComputerName | |
$sessions = $sessionsOutput | ForEach-Object { $_ -replace '\s{2,22}', ',' } | ConvertFrom-Csv | |
$userColumnNames = @('ПОЛЬЗОВАТЕЛЬ', 'USERNAME') | |
$userColumn = $null | |
foreach ($columnName in $userColumnNames) { | |
if ($sessions[0].PSObject.Properties.Name -contains $columnName) { | |
$userColumn = $columnName | |
break | |
} | |
} | |
if ($null -eq $userColumn) { | |
Write-Error "Не удалось определить колонку с именем пользователя." | |
return | |
} | |
if ([string]::IsNullOrWhiteSpace($ExcludedUsers)) { | |
return $sessions.ID | |
} | |
$excludedUsersArray = $ExcludedUsers -split ',' | ForEach-Object { $_.Trim() } | |
$filteredSessions = $sessions | Where-Object { | |
$excludedUsersArray -notcontains $_.$userColumn | |
} | |
return $filteredSessions.ID | |
} | |
function Stop-Sessions { | |
param ( | |
[string]$ComputerName = "$env:COMPUTERNAME", | |
[string]$ExcludedUsers = "" | |
) | |
$sessionIDs = Get-FilteredSessionIDs -ComputerName $ComputerName -ExcludedUsers $ExcludedUsers | |
if (-not $sessionIDs) { | |
Write-Output "Нет сеансов для завершения." | |
return | |
} | |
foreach ($sessionID in $sessionIDs) { | |
$sessionID = [int]$sessionID | |
rwinsta $sessionID /server:$ComputerName | |
} | |
} | |
Stop-Sessions -ExcludedUsers "User" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment