I am having issues with the script overwriting itself and not holding onto the values. The only thing exported to the CSV is the list of active users on the last server, instead of all the users and servers together.
Thank you!
What this script does: It filters out users that have been active in for more than 60min or are disconnected. For the disconnect script, I used a simple open source script from a MS contributor, found here. I've added the complete code with all the functions to my github gist:https://gist.github.com/ruslive109/a56837bb84187b522797b2abb19d6acf
$Servers = Get-Content 'H:\demo\computernames.txt'
$openservers =@()
foreach ($Server in $Servers)
{
if (-not( Test-Connection $Server -Count 1 -Quiet )) { continue }
if (-not( Convert-QueryToObjects $Server -ErrorAction SilentlyContinue))
{
$openservers += $server
$openservers | Out-File 'H:\demo\session\openservers.txt'
}
else
{
Convert-QueryToObjects -Name $Server |Where-Object{ {@('Disconnected','Active') -contains $_.SessionState} | Select-Object {@{Name='Server Name';Expression={$_.ComputerName}},
@{Name='Username'; Expression={$_.Username}}, @{Name='Session State'; Expression={$_.SessionState}}, @{Name='Idle Time'; Expression={$_.IdleTime}},
@{Name='ID'; Expression={$_.ID}} }}| Export-Csv 'H:\demo\session\run11.csv' -NoTypeInformation -Force
Import-Csv 'H:\demo\session\run11.csv' | Where-Object { ($_.SessionState -eq 'Disconnected') -or (($_.IdleTime -like "*:*") -and ($_.IdleTime -gt "00:59"))} |
ForEach-Object {
Disconnect-LoggedOnUser -ComputerName $_.ComputerName -Id $_.ID -Verbose
}
}
}