<#
This is a selection of PS Snippets to quickly display some
StifleR Statistics without using the dashboards
#>

#Server processing stats#
#Use this to check the health of the SignalR Hub in processing messages etc
#Same stats as displayed in the Performance dashboard
#Generally - XXXXInitiated should = XXXXCompleted
gwmi -namespace root\StifleR -Query "Select * from StiflerEngine WHERE id = 1" `
| FL -property NumberOfClients, ActiveNetworks, ActiveRedLeaders,HubConnectionInitiated,HubConnectionCompleted,`
ClientINfoInitiated, ClientInfoCompleted, JobReportInitiated ,JobReportCompleted,JobReporDeltatInitiated,JobReportDeltaCompleted
#### END Server Processing stats

#### Display the top nn Clients - Time since last checkin (this checks for 'dead' clients that have disconnected but are still on the StifleR server))
gwmi -namespace root\StifleR -Query "Select * From Clients"| sort-object -Property `
 lastcheckintime  | select-object ComputerName,NetworkID,@{Name='Last Checkin Time ';Expression={$_.ConvertToDateTime( $_.lastcheckintime)}}, `
   @{Name='TimeSinceLastCheckin';Expression={New-Timespan -End $_.ConvertToDateTime( $_.lastcheckintime)}} -First 30 |ft -AutoSize
#### END Client Checking Time

### Check for duplicate clients - performs 2 counts - unique/all - both counts should be the same
$UC = gwmi -namespace root\StifleR -Query "Select * From Clients"  | Get-Unique
$AC = gwmi -namespace root\StifleR -Query "Select * From Clients"
cls
Write-Host "Count of Unique Clients " $UC.Count
Write-Host "Count of Actual Clients " $AC.Count
### END Check For Duplicates

### Queue Per Subnet###
### Shows the BITS and Delivery Optimization queue at each subnet so that you can spot bottlenecks
$AllTX = gwmi -namespace root\StifleR -Query "Select * from Clients" | Select-Object TotalQueueSize_BITS,TotalQueueSize_DO, NetworkID
$alltx |Group-Object NetworkID | %{
    New-Object psobject -Property @{
        NetworkID = $_.Name
        BITSTotal =“{0:N2}” -f (($_.Group | Measure-Object TotalQueueSize_BITS -Sum).Sum /1MB)
        DOTotal = “{0:N2}” -f(($_.Group | Measure-Object TotalQueueSize_DO -Sum).Sum /1MB)
        Clients = $_.Count
    }
}|  Sort-Object -Property Clients | FT -AutoSize
Write-Host "Total CLient Count: " $alltx.count

###END Queue Per Subnet###
 
###Get the total outstanding downloads for BITS and DO
$AllTX = gwmi -namespace root\StifleR -Query "Select * from Clients " | Select-Object TotalQueueSize_BITS,TotalQueueSize_DO
$BITSTotal = “{0:N2}” -f (($AllTX | measure-object TotalQueueSize_BITS -sum).sum /1GB)
$DOTotal = “{0:N2}” -f (($AllTX | measure-object TotalQueueSize_DO -sum).sum /1GB)
cls
Write-Host ""
Write-Host " Total in BITS Q $BITSTotal GB"
Write-Host " Total in DO Q $DOTotal GB"
Write-host " Number of Clients " $alltx.Count
Write-Host ""
###END Get the total outstanding downloads for BITS and DO

### Show All Delivery Optimization Jobs
cls
  gwmi -namespace root\StifleR -Query "Select * from Downloads WHERE TYPE = 'DO'" `
  | select-object State, @{L='Type';E={$_.CurrentJobStifleRDefinitionName}}, DefinitionIdentfier,`
  @{Name='Job Size (MB)';Expression={ “{0:N2}” -f ($_.Size /1MB)}},`
  @{Name='From Origin (MB) ';Expression={ “{0:N2}” -f ($_.CurrentJobFromOriginInBytes /1MB)}},`
  @{Name='From P2P (MB) ';Expression={ “{0:N2}” -f ($_.CurrentJobFromPeersInBytes /1MB)}},`
  @{Name='Time Completed ';Expression={$_.ConvertToDateTime( $_.Completed)}} | FT -AutoSize
  ### END Show All Delivery Optimization Jobs ###
 ###### RED LEADERS ######
 #Select all Currently Transferring Red Leaders and show the Queue etc
 gwmi -namespace root\StifleR -Query "Select * from Clients WHERE ActivelyTRansferring = True AND IsRedLeader = TRUE" `
 | Select-Object ComputerName, @{L='BITS Job';E={$_.CUrrentJobName_BITS}}, Bandwidthallowed, `
  NetworkID, @{L='BITS B/W   ';E={$_.MinuteBandwidthUsed_BITS}},@{L='DO B/W   ';E={$_.MinuteBandwidthUsed_DO}}`
  , @{L='BITS Queue';E={“{0:N2}” -f ($_.TotalQueueSize_BITS /1MB)}},@{L='DO Queue';E={“{0:N2}” -f ($_.TotalQueueSize_DO /1MB)}} |FT -AutoSize
 
  ##END Show Red Leaders Queue
  gwmi -namespace root\StifleR -Query "Select * from Clients" | select-object version
 
 ### Show all clients on a specific subnet ###
gwmi -namespace root\StifleR -Query "Select * from Clients WHERE NetworkID = '172.31.28.0'" | `
Select-Object ComputerName,@{L='RL ?';E={$_.IsRedLeader}}, Activelytransferring, BandwidthAllowed,  `
@{L='BITS Job';E={$_.CUrrentJobName_BITS}},  @{L='BITS B/W   ';E={$_.MinuteBandwidthUsed_BITS}},@{L='DO B/W   ';E={$_.MinuteBandwidthUsed_DO}}`
  , @{L='BITS Queue';E={“{0:N2}” -f ($_.TotalQueueSize_BITS /1MB)}},@{L='DO Queue';E={“{0:N2}” -f ($_.TotalQueueSize_DO /1MB)}}, NetworkID |FT -AutoSize
### END Show all clients on a specific subnet ###
### Show a single Client - quick snapshot ###
$Cname = Read-Host -Prompt 'Input the Computer Name to view some stats..'
 gwmi -namespace root\StifleR -Query "Select * from Clients WHERE computername = '$Cname'" `
 | select-object OSBuild,Activelytransferring, IsRedLeader, bandwidthallowed,  CurrentJobName_BITS, minutebandwidthused_BITS, minuteBandwidthused_DO,CurrentJobFromPeersInBytes_BITS,DOJobs
 ## get info from the downloads table for that machine
 gwmi -namespace root\StifleR -Query "Select * from Downloads WHERE ID Like '%$Cname%'" | select-object Name, `
 @{L='Definition';E={$_.CurrentJobStifleRDefinitionName}}, State,Priority, StifleRID, @{Name='Computer Name';Expression={$_.ID.Substring(0,8)}}, `
 @{L='Server (MB)';E={“{0:N2}” -f ($_.CurrentJobFromOriginInBytes /1MB)}},@{L='P2P (MB)';E={“{0:N2}” -f ($_.CurrentJobFromPeersInBytes /1MB)}}| FT -AutoSize
 ### END Show a single Client - quick snapshot ###

 ##### DOWNLOADS ####
 ### Show all downloads from a specific machine - insert the Computer Name where it says xxxxx12345 ###
gwmi -namespace root\StifleR -Query "Select * from Downloads WHERE ID Like '%1021346x%'" | select-object Name, CurrentJobStifleRDefinitionName, State, @{Name='Computer Name';Expression={$_.ID.Substring(0,8)}}
 ### END Show all downloads from a specific machine ###
 ### Show all downloads currently in an Error state ###
gwmi -namespace root\StifleR -Query "Select * from Downloads WHERE State Like '%Error%'" `
| select-object Name,Type, State, @{Name='Computer Name';Expression={$_.ID.Substring(0,8)}} | FT -AutoSize
 ### END Show all downloads currently in an Error state ###
 ###Display stats every 3 secs for all transferrinf subnets ###
 $timeout = New-TimeSpan -Minutes 5
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $timeout){
        if ($host.UI.RawUI.KeyAvailable) {
            $key = $host.UI.RawUI.ReadKey()
            break
            }
cls
gwmi -namespace root\StifleR -Query "Select * from Clients WHERE ActivelyTRansferring = True And IsRedLeader = True" | Select-Object ComputerName,Activelytransferring, bandwidthallowed,  NetworkID, MInuteBandwidthUsed_BITS,MinuteBandwidthUsed_DO | FT -AutoSize
start-sleep -seconds 5         
     }
 ###END Display stats every 3 secs for all transferrinf subnets ###
 #### EXPORTING DATA TO CSV ####

### Dump all BITS/DO Jobs ###
 $allDOJobs =  gwmi -namespace root\StifleR -Query "Select * from Downloads WHERE TYPE = 'DO'" #change to Type = 'BITS' if required or just remove the WHERE for all types
 foreach ( $DOJob in $allDOJobs ) {
 $Computer = $DOJob.ID
  [PSCustomObject]@{
       Computer = $Computer.Substring(0,8)
       JobName =  $DOJob.CurrentJobStifleRDefinitionName
       DefinitionID = $DOJob.DefinitionIdentfier
       JobSize =  $DOJob.Size
       BytesFromServer = $DOJob.CurrentJobFromOriginInBytes
       BytesFromPeers = $DOJob.CurrentJobFromPeersInBytes
       TimeCompleted = $DOJob.Completed
      
       } | Export-Csv C:\AllDOJobs.csv -notype -Append
  }

 ### END Dump all DO Jobs ###

 ###Dump some subnet info - "SubnetID","ActiveClients","TargetBW","UsedBW","PercentUsed" - so you can see if B/W is bein over/under used ###
  $allSubs = gwmi -namespace root\StifleR -Query "Select * from Subnets where ActiveClients > 0"
foreach ( $Sub in $allSubs ) {
$PerCentUsed = “{0:P2}” -f ($Sub.CurrentBandwidth / $Sub.TargetBandwidth)
$UsedBW = “{0:N2}” -f ($Sub.CurrentBandwidth)
  [PSCustomObject]@{
       SubnetID = $Sub.SubnetID
       ActiveClients =  $Sub.ActiveClients
       TargetBW = $Sub.TargetBandwidth
       UsedBW =  $UsedBW
       PercentUsed = $PerCentUsed
      
       } | Export-Csv C:\ActiveSubnetBWPercent.csv -notype -Append
 
 }
 ### END Dump some subnet B/W info ###
 ### Dump all clients  - StifleR version, OS version etc ###
 $allClients =  gwmi -namespace root\StifleR -Query "Select * From Clients"
 foreach ( $Cli in $allClients ) {
  [PSCustomObject]@{
       Computer = $Cli.Computername
       ConnID =  $Cli.ConnectionID
       Version = $Cli.Version
       OSBuild =  $Cli.OSBuild
      
       } | Export-Csv C:\AllClients2.csv -notype -Append
}
 ### END Dump all clients ###

 #####Get all active transfers, work out % of allowed bandwidth being used, and export to .CSV ###
$allCli = gwmi -namespace root\StifleR -Query "Select * from Clients where ActivelyTransferring = True"
foreach ( $Client in $allCli ) {
if ($Client.CurrentJobSize -eq 0){$Jobsize = 1} else {$Jobsize = $Client.CurrentJobSize}
$PerCentUsed = “{0:P2}” -f ($Client.BandwidthUsed / $Client.BandwidthAllowed)
$UsedBW = “{0:N2}” -f ($Client.BandwidthUsed)
$PeerBWBITS = “{0:N2}” -f ($Client.peerbandwidthused_BITS)
$PeerBWDO = “{0:N2}” -f ($Client.peerbandwidthused_DO)
$PercentJobComplete = “{0:P2}” -f ($Client.CurrentJobTransferred / $Jobsize)
#display some basic stats - comment this next line out if you don't want to display
$Client.ComputerName  + "  BW Allowed: " +  $Client.bandwidthallowed + "  Used: " + $UsedBW  + "  Percent: " + $PerCentUsed + "  PeerBW BITS: " + $PeerBWBITS +"  PeerBW DO: " + $PeerBWDO + " % Complete: " + $PercentJobComplete
 #output more stats to .csv
  [PSCustomObject]@{
       IsRedLeader = $Client.IsRedLeader
       BITSQSize = $Client.JobsOnClient
       CurrentJob = $Client.CurrentJobName
       CurrentJobStifleRDefinitionName = $Client.CurrentJobStifleRDefinitionName
       NetworkID =  $Client.NetworkId
       SystemName = $Client.ComputerName
       AllowedBW = $Client.bandwidthallowed
       UsedBW =  $UsedBW
       PercentUsed = $PerCentUsed
       PeerBWBITS = $PeerBWBITS
       PeerBWDO = $PeerBWDO
       } | Export-Csv C:\ActiveClientBWPercent.csv -notype -Append
 
 }
 ### END Get all Active Transfers ###