25. November 2015

PowerShell Version: >1
Modules: none
I needed a way to log the first local interface’s gateway for debugging reasons, here is how I did it:
$netcards = Get-WmiObject Win32_NetworkAdapterConfiguration
# reset the array with every run of the script
$netcard_gateway_array = @()
# ...we might have more than one network interface present
foreach ($netcard in $netcards)
{
# don't show interfaces without default gw
if ($netcard.DefaultIPGateway -ne $null)
{
# for more than one interface present we need an array to store the information
$netcard_gateway_array += $netcard.DefaultIPGateway
}
}
# receive only the first interface's gateway
$netcard_gateway_array[0]
24. November 2015

PowerShell Version: >1
Modules: none
This script will check your TS servers for a session with $env:Username and logoff that session. This of course only works if $env:username on client and TS are the same 😉 Also I made an effort to make it work on PS v1 for all clients to be able to execute this.
# mention all terminal servers here
$server1 = "SERVER1-FQDN"
$server2 = "SERVER2-FQDN"
# build an array for the foreach
$ts_server_array = @()
$ts_server_array += $server1
$ts_server_array += $server2
# do this for each terminal server in the environment
foreach ($ts_server in $ts_server_array)
{
# use qwinsta for oldschool session log off (maximum compatibility)
$qwinsta = qwinsta /server:$ts_server | ForEach-Object {$_.Trim() -replace "\s+",","}
$activeusersTS = @()
foreach ($item in $qwinsta)
{
if ($item -like "rdp*")
{
# remove the "rdp-tcp#... if present"
$activeusersTS += $item -replace "^(.*?),",""
}
else
{
# if there is no "rdp-tcp#..." in the line we're good
$activeusersTS += $item
}
}
foreach ($user in $activeusersTS)
{
if ($user -like "$env:Username*")
{
# get User line and remove everything left but the Session ID
$userid = $user -replace "^(.*?),","" -replace ",.*",""
# logoff User
rwinsta $userid /server:$ts_server
}
}
}