Logoff all user sessions on multiple computers

I have a powershell script which is meant to logoff user sessions that are connected to a computer.
The script works in 2 parts 
1. When you run it and specify the target computer (This part is working 100%)
2. When you run it & get content from a txt file with a list of computers (this is the part that is not working)
I have noticed that it does select the a computer name from the text file. Hence the command runs without the $computer parameter logging you off your computer not the remote sessions on the target computer.
See below the script

 

<#

.SYNOPSIS   

Script to logoff all users logged on to specified computers

 

.DESCRIPTION 

The script can use either a plaintext file or a computer name as input and will logoff any user sessions that are logged on Active or Disconnected

.PARAMETER InputFile

A path that contains a plaintext file with computer names

.PARAMETER Computer

This parameter can be used instead of the InputFile parameter to specify a single computer or a series of computers using a comma-separated format

.EXAMPLE   

.\Remote-Logoff.ps1 -Computer Server01

Description:

Will logoff all user sessions on Server01

 

.EXAMPLE   

.\Remote-Logoff.ps1 -InputFile C:\ListofComputers.txt

Description:

Will logoff all user sessions on all servers and computernames listed in the ListofComputers file

 

#>

param(

    [Parameter(ParameterSetName='InputFile')]

    [string]

        $InputFile,

    [Parameter(ParameterSetName='Computer')]

    [string]

        $Computer

)

<#

.SYNOPSIS

    Function that resolves computer names and can exit script if resolution fails

#>

 

if (!$InputFile) {

if (!$Computer) {

$Computer = Read-Host "Please input computer name"

}

[string[]]$Computer = $Computer.Split(',')

$Computer | ForEach-Object {

$_

Write-Host "Logging of all logged in users on `'$_`'"

try {

query user /server:$Computer 2>&1 | select -skip 1 | foreach {

            logoff ($_ -split "\s+")[-6] /server:$Computer

            }

Write-Host -ForegroundColor Green "Successfully completed command on `'$_`'"

} catch {

Write-Warning "$_"

}

}

}

else {

if (!(Test-Path -Path $InputFile)) {

Write-Warning "Input file not found, please enter correct path"

exit

}

Get-Content -Path $InputFile | ForEach-Object {

Write-Host "Logging of all logged in users on `'$_`'"

try {

query user /server:$Computer 2>&1 | select -skip 1 | foreach {

            logoff ($_ -split "\s+")[-6] /server:$Computer

            }

            Write-Host -ForegroundColor Green "Successfully completed command"

} catch {

Write-Warning "$_"

}        

}

}

Parents
  • Under this line:

    Get-Content -Path $InputFile | ForEach-Object {

    Add the following line:

    $Computer = $_

     

    See if that fixes the problem. I don't have an appropriate server to test it myself.

Reply Children
No Data