Skip to content

Instantly share code, notes, and snippets.

@weipah
Created November 26, 2012 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weipah/4148010 to your computer and use it in GitHub Desktop.
Save weipah/4148010 to your computer and use it in GitHub Desktop.
Poll a list of Windows Terminal Servers for a specific User (Multithreading attempt 1)
function Get-XTSSession() {
Param ([Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, HelpMessage="UserName?")]
$User )
$aco_servers = "C:\Users\adm-ml\Documents\WindowsPowerShell\Modules\PSTerminalServices\aco-terminal-servers.txt"
$workingDirectory = (get-location)
if ($user.gettype().fullname -eq "System.String") {
if ($user -ne $null -and $user.length -gt 0) {
$username = $user
} else {
write "Param $user is $null or empty."
return
}
} elseif ($user.getType().fullname -eq "Microsoft.ActiveDirectory.Management.ADUser") {
if ($user.samaccountname -ne $null -and $user.samaccountname.length -gt 0) {
$username = $user.samaccountname
} else {
write "$user.samaccountname is not a valid username."
return
}
} else {
write "This function can not handle Type " $user.getType().fullname
return
}
if (test-path $aco_servers) {
Get-Content $aco_servers | %{
# Define what each job does
[ScriptBlock]$initScript = [ScriptBlock]::Create("set-location " + $workingDirectory + "; Import-Module PSTerminalServices;")
[ScriptBlock]$Scriptblock = {
param([String]$username,[String]$server)
get-tssession -ComputerName $server -State active -Username $username
}
# Execute the jobs in parallel
Start-Job -name $_ -InitializationScript $initScript -ScriptBlock $Scriptblock -ArgumentList $username,$_ | out-null
}
# wait for jobs to complete
wait-job -state running|out-null
# Retrieve the information from the completed jobs
$sessions = @()
Get-Job -state completed|?{$_.hasmoredata -eq $true -and $_.name -match '^(rd-ts-)[0-9]{3}$'} |%{$sessions += (receive-job $_); Add-Member -InputObject $sessions[$sessions.count-1] -MemberType NoteProperty -Name Servername -Value $_.name}
# clear all completed jobs
get-job -state completed|remove-job
# return results
return $sessions
} else {
write "The Path '" $aco_servers "' is not valid."
return
}
Exit 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment