Skip to content

Instantly share code, notes, and snippets.

@lordmuffin
Last active February 7, 2017 19:35
Show Gist options
  • Save lordmuffin/fcd63534269b28617597cbd8a8914d28 to your computer and use it in GitHub Desktop.
Save lordmuffin/fcd63534269b28617597cbd8a8914d28 to your computer and use it in GitHub Desktop.
# This is a remote logoff script intended to logoff any user off of a series of remote systems in a domain.
# This will also generate a logfile in the folder that it is run in. - This should be helpfull for any troubleshooting that maybe required.
# Writtin by: Andrew Jackson
#Import Logging Function
<#
.SYNOPSIS
RemoteLogoffUser
.DESCRIPTION
RemoteLogoffUser DESCRIPTION
.PARAMETER ou
Organization Unit
.PARAMETER username
username
.EXAMPLE
C:\PS> .\remotelogoff.ps1 -h
<Displays this help message>
.EXAMPLE
C:\PS> .\remotelogoff.ps1 -help
<Displays this help message>
.EXAMPLE
C:\PS> .\remotelogoff.ps1 -ou "DC=domain,DC=com" -username "first.last"
<Runs against entire OU "DC=domain,DC=com" aginst user "first.last">
#>
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]$ou,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]$username,
[parameter(Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[String]$exception
)
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
<#
.Synopsis
Write-Log writes a message to a specified log file with the current time stamp.
.DESCRIPTION
The Write-Log function is designed to add logging capability to other scripts.
In addition to writing output and/or verbose you can write to a log file for
later debugging.
.NOTES
Created by: Jason Wasser @wasserja
Modified: 11/24/2015 09:30:19 AM
Changelog:
* Code simplification and clarification - thanks to @juneb_get_help
* Added documentation.
* Renamed LogPath parameter to Path to keep it standard - thanks to @JeffHicks
* Revised the Force switch to work as it should - thanks to @JeffHicks
To Do:
* Add error handling if trying to create a log file in a inaccessible location.
* Add ability to write $Message to $Verbose or $Error pipelines to eliminate
duplicates.
.PARAMETER Message
Message is the content that you wish to add to the log file.
.PARAMETER Path
The path to the log file to which you would like to write. By default the function will
create the path and file if it does not exist.
.PARAMETER Level
Specify the criticality of the log information being written to the log (i.e. Error, Warning, Informational)
.PARAMETER NoClobber
Use NoClobber if you do not wish to overwrite an existing file.
.EXAMPLE
Write-Log -Message 'Log message'
Writes the message to c:\Logs\PowerShellLog.log.
.EXAMPLE
Write-Log -Message 'Restarting Server.' -Path c:\Logs\Scriptoutput.log
Writes the content to the specified log file and creates the path and file specified.
.EXAMPLE
Write-Log -Message 'Folder does not exist.' -Path c:\Logs\Script.log -Level Error
Writes the message to the specified log file as an error message, and writes the message to the error pipeline.
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Write-Log-PowerShell-999c32d0
#>
function Write-Log
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("LogContent")]
[string]$Message,
[Parameter(Mandatory=$false)]
[Alias('LogPath')]
[string]$Path='C:\Logs\PowerShellLog.log',
[Parameter(Mandatory=$false)]
[ValidateSet("Error","Warn","Info")]
[string]$Level="Info",
[Parameter(Mandatory=$false)]
[switch]$NoClobber
)
Begin
{
# Set VerbosePreference to Continue so that verbose messages are displayed.
$VerbosePreference = 'Continue'
}
Process
{
# If the file already exists and NoClobber was specified, do not write to the log.
if ((Test-Path $Path) -AND $NoClobber) {
Write-Error "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name."
Return
}
# If attempting to write to a log file in a folder/path that doesn't exist create the file including the path.
elseif (!(Test-Path $Path)) {
Write-Verbose "Creating $Path."
$NewLogFile = New-Item $Path -Force -ItemType File
}
else {
# Nothing to see here yet.
}
# Format Date for our Log File
$FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Write message to error, warning, or verbose pipeline and specify $LevelText
switch ($Level) {
'Error' {
Write-Error $Message
$LevelText = 'ERROR:'
}
'Warn' {
Write-Warning $Message
$LevelText = 'WARNING:'
}
'Info' {
Write-Verbose $Message
$LevelText = 'INFO:'
}
}
# Write log entry to $Path
"$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append
}
End
{
}
}
#Pre Variables
$date = get-date -f MM-dd-yyyy_HH_mm_ss
$log = new-item -itemtype file -path ($ScriptPath + "\" + $username + "-" + $date + "-log.log")
#Get Variables
#Write-Log -Path $log -Message "$($ScriptPath)"
$servers = $null
$testedservers = new-item -itemtype file -path ($ScriptPath + "\" + $username + "-" + $date + "-srv.txt")
$i = $null
Write-Log -Path $log -Message "Grabbing Variables completed."
#Getting servers from OU
try {
Write-Log -Path $log -Message "Searching OU for servers..."
IF(!$exception){$servers = Get-ADComputer -Filter * -SearchBase $ou | Select Name}
ELSE{$servers = Get-ADComputer -Filter {Name -notlike $exception} -SearchBase $ou | Select Name}
}
catch {Write-Log -Path $log -Message "Searching OU for servers failed!!!"}
#Test for servers responding
Foreach($s in $servers){
if(Test-Connection -Cn $s.Name -BufferSize 16 -Count 1 -ea 0 -quiet)
{
$i++
Add-Content -Path $testedservers.Name "$($s.Name)"
Write-Log -Path $log -Message "Validated connectivity to $($s.Name) ## $($i) of $($servers.count)"
}
ELSE {$i++; Write-Log -Path $log -Message "Unable to connect to $($s.Name) Removing from serverlist. ## $($i) of $($servers.count)"}
}
#Get Server from
#Reset Counter
$i = $null
$testedserversout = gc $testedservers.VersionInfo.FileName
Foreach ($server in $testedserversout) {
Try {
$i++
Write-Log -Path $log -Message "Querying $server to see if $username is logged in... ## $($i) of $($testedservers.count)"
query user /server:$server 2>&1 | ? { $_ -match $username } |
Foreach {
Write-Log -Path $log -Message "Logging $username off $server... ## $($i) of $($testedservers.count)"
logoff ($_ -split "\s+")[-6] /server:$server
Write-Log -Path $log -Message "$username logged off $server successfully ## $($i) of $($testedservers.count)"
}
}
Catch {$ii; Write-Log -Path $log -Message "$username logged off $server FAILED! ## $($i) of $($testedservers.count)"}
}
#Cleanup
Write-Log -Path $log -Message "Removing $($testedservers.VersionInfo.FileName)..."
Remove-Item $testedservers
Write-Log -Path $log -Message "Removed $testedservers.VersionInfo.FileName Completed"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment