Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $content = "H:democomputernames.txt" #please input where the list of servers is found (in a txt doc please)
- $input = "H:demosessionrun11.csv" #please input where you want the csv to be exported (this includes all the active and disconnected servers)
- $export ='H:demosessionopenservers.txt' #please input where you want to 'open servers' (no users) to be exported.
- #and that does it. cheers!
- if (Test-Path $input) {
- Clear-Content $input
- }
- $Servers = Get-Content "$content"
- $openservers = @()
- #THE LOOP THAT FILTERS THE SERVERS MENTIONED IN THE LIST ABOVE
- foreach ($Server in $Servers) {
- #tests the connection to the server (general test for the entire server)
- if (-not (Test-Connection $Server -Count 1 -Quiet)) { continue }
- #if their are no users logged in (hence the count of zero), push that server name onto a txt doc
- if (-not (Convert-QueryToObjects $Server -ErrorAction SilentlyContinue)) {
- $openservers += $server
- $openservers | Out-File $export #**TXT EXPORT**#
- }
- #if there are users logged onto the server, make sure they are either in disc or active state and push all the session details onto a seperate csv
- else {
- Convert-QueryToObjects -Name $Server | Where-Object {
- @('Disconnected','Active') -contains $_.SessionState
- }|Export-Csv $input -NoTypeInformation -Append
- # does the append so each time the content is kept (however, the issue of duplicate content arose (hence the fix above).
- }
- } #concludes the first foreach loop
- #<--- the folllowing function works with PsExec(external program)
- $openservers = Get-Content "$export" #**TXT IMPORT**#
- #for each server in the server list, it will check to make sure its online (Again).
- foreach($openserver in $openservers){
- if( Test-Connection -Cn $openserver -Quiet) {
- H:PsToolsPsExec.exe \$openserver change logon /enable # calls an external tool and passes it the
- }
- else {
- Write-Host("the server>> $openserver is NOT online") -ForegroundColor DarkYellow
- }
- }
- #THIS IMPORTS FROM THE EXPORTED FILE PATH#
- Import-Csv $input | Where-Object {
- ($_.SessionState -eq 'Disconnected') -or #if its disconnected or
- (($_.IdleTime -like "*:*") -and ($_.IdleTime -gt "00:59")) #idle time is over an hour, kindly do this:
- } | ForEach-Object { #disconnect the session by using the server name and session ID
- Disconnect-LoggedOnUser -ComputerName $_.ComputerName -Id $_.ID -Verbose
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement