├── InfluxDB-Powershell-Module └── InfluxDB-Powershell-Module.psm1 ├── LICENSE ├── Powershell Monitoring Examples ├── Citrix Xenapp │ ├── README.txt │ ├── XAmaintenance_template.csv │ └── citrix7servers2influxdb.ps1 ├── DHCP │ ├── DHCP2influxdb.csv │ └── DHCP2influxdb.ps1 ├── File Servers │ ├── clusterdrives.csv │ ├── drivestatus2influxdb.ps1 │ ├── quotas(2012).ps1 │ └── quotaswarnings2influxdb.ps1 ├── NTP Servers │ └── NTPsync2influxdb.ps1 └── VMware vSphere │ ├── README.txt │ ├── vmIOPS2influxdb.ps1 │ ├── vmcreationdeletion2influxdb.ps1 │ └── vmdatastores2influxdb.ps1 ├── Query2influxdb.ps1 └── README.md /InfluxDB-Powershell-Module/InfluxDB-Powershell-Module.psm1: -------------------------------------------------------------------------------- 1 | function convertto-unixtime { 2 | param( 3 | [parameter(Position = 0, 4 | Mandatory = $false)] 5 | [datetime]$DateTime, 6 | [parameter(Position = 1, 7 | Mandatory = $false)] 8 | [string]$precision='ns' 9 | ) 10 | [datetime]$EpochOrigin = "1970/01/01 00:00:00" 11 | switch($precision){ 12 | 's'{ 13 | if ($DateTime -eq $null){ $unixtime = [int64](New-TimeSpan -Start $EpochOrigin -End ([DateTime]::Now).ToUniversalTime()).Totalseconds } 14 | else { $unixtime = [int64](New-TimeSpan -Start $EpochOrigin -End $DateTime.ToUniversalTime()).Totalseconds } 15 | } 16 | 'ms'{ 17 | if ($DateTime -eq $null){ $unixtime = [int64](New-TimeSpan -Start $EpochOrigin -End ([DateTime]::Now).ToUniversalTime()).TotalMilliseconds } 18 | else { $unixtime = [int64](New-TimeSpan -Start $EpochOrigin -End $DateTime.ToUniversalTime()).TotalMilliseconds } 19 | 20 | } 21 | 'ns'{ 22 | if ($DateTime -eq $null){ $milliseconds = [int64](New-TimeSpan -Start $EpochOrigin -End ([DateTime]::Now).ToUniversalTime()).TotalMilliseconds } 23 | else { $milliseconds = [int64](New-TimeSpan -Start $EpochOrigin -End $DateTime.ToUniversalTime()).TotalMilliseconds } 24 | #convert milliseconds to nanoseconds 25 | $unixtime = $milliseconds * 1000000 26 | } 27 | } 28 | return $unixtime 29 | } 30 | Function convertto-datetime { 31 | param( 32 | [parameter(Position = 0, 33 | Mandatory = $true)] 34 | [int64]$unixtime, 35 | [parameter(Position = 1, 36 | Mandatory = $false)] 37 | [string]$precision='ns' 38 | ) 39 | switch($precision){ 40 | 'ns'{ 41 | #convert nanoseconds to milliseconds 42 | $milliseconds = $unixtime / 1000000 43 | } 44 | 'ms'{ 45 | $milliseconds = $unixtime 46 | } 47 | 's'{ 48 | $milliseconds = $unixtime * 1000 49 | } 50 | } 51 | 52 | [datetime]$EpochOrigin = "1970/01/01 00:00:00" 53 | $datetime = $EpochOrigin.AddMilliseconds($milliseconds) 54 | 55 | return $datetime 56 | } 57 | function write-influxDB() { 58 | param( 59 | [parameter(Position = 0, 60 | Mandatory = $true)] 61 | [string]$database, 62 | 63 | [parameter(Position = 1,Mandatory = $true,ValueFromPipeline)] 64 | [string]$lineprotocol, 65 | 66 | [parameter(Position = 2)] 67 | [string]$server = "serverinfluxdb01.sistemaswin.com" 68 | ) 69 | 70 | 71 | $url = "http://{0}:8086/write?db={1}" -f $server, $database 72 | Invoke-webrequest -UseBasicParsing -Uri $url -Body $lineprotocol -method Post 73 | } 74 | Function Write-SecuredInfluxDB{ 75 | param( 76 | [parameter(Position = 0, 77 | Mandatory = $true)] 78 | [string]$database, 79 | [parameter(Position = 1,Mandatory = $true,ValueFromPipeline)] 80 | [string]$lineprotocol, 81 | [parameter(Position = 2)] 82 | [string]$server = "serverinfluxdb01.sistemaswin.com", 83 | [string]$username, 84 | [string]$password, 85 | [PScredential]$credential 86 | ) 87 | $url = "https://{0}:8086/write?db={1}" -f $server, $database 88 | if (-not $credential){ 89 | $pass = ConvertTo-SecureString -String $password -asPlainText -Force 90 | $credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$pass 91 | } 92 | if($PSVersionTable.PSVersion.Major -lt 7){ 93 | # Código para ignorar el certificado de https de influx 94 | $code= @" 95 | using System.Net; 96 | using System.Security.Cryptography.X509Certificates; 97 | public class TrustAllCertsPolicy : ICertificatePolicy { 98 | public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { 99 | return true; 100 | } 101 | } 102 | "@ 103 | Add-Type -TypeDefinition $code -Language CSharp 104 | [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy 105 | # Fin codigo de ignorado certificado https 106 | Invoke-webrequest -UseBasicParsing -Uri $url -Body $lineprotocol -method Post -Credential $credential 107 | } 108 | else{ 109 | Invoke-webrequest -UseBasicParsing -Uri $url -Body $lineprotocol -method Post -Credential $credential -SkipCertificateCheck 110 | } 111 | } 112 | Function write-InfluxLogging(){ 113 | param( 114 | [int]$errorcode, 115 | [int]$duration, 116 | [Parameter(ValueFromPipeline)] 117 | [string]$msg 118 | ) 119 | $arrayfieldset=@() 120 | $arrayfieldset+='value=1i' 121 | if ($errorcode){$arrayfieldset+='errorcode={0}i' -f $errorcode} 122 | if ($duration){$arrayfieldset+='duration={0}i' -f $duration} 123 | if ($msg){$arrayfieldset+='msg="{0}"' -f $msg} 124 | $fieldset=$arrayfieldset -join "," 125 | $measurement='powershell' 126 | $tagset= 'servername={0},username={1},script={2}' -f $env:computername.toupper(),$env:username,((split-path $MyInvocation.scriptname -leaf) -replace " ","\ ") 127 | $body="$measurement,$tagset $fieldset" 128 | write-influxdb "logs" $body 129 | } 130 | 131 | function read-influxDB { 132 | 133 | param( 134 | [parameter(Position = 0, 135 | Mandatory = $true)] 136 | [string]$database, 137 | 138 | [parameter(Position = 1,Mandatory = $true,ValueFromPipeline)] 139 | [string]$query, 140 | 141 | [parameter(Position = 2)] 142 | [string]$server = "serverinfluxdb01.sistemaswin.com", 143 | [PSCredential]$credential 144 | ) 145 | 146 | if ($server -match ":\d"){$url = "{0}/query?db={1}&q={2}" -f $server,$database,$query} 147 | else{$url = "{0}:8086/query?db={1}&q={2}" -f $server,$database,$query} 148 | $params = @{} 149 | if($PSVersionTable.PSVersion.Major -lt 7){ 150 | if($server -match "^https"){ 151 | #[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } 152 | $code= @" 153 | using System.Net; 154 | using System.Security.Cryptography.X509Certificates; 155 | public class TrustAllCertsPolicy : ICertificatePolicy { 156 | public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { 157 | return true; 158 | } 159 | } 160 | "@ 161 | Add-Type -TypeDefinition $code -Language CSharp 162 | [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy 163 | } 164 | if($credential){ 165 | $params.add('credential',$credential) 166 | } 167 | } 168 | else{ 169 | if($server -match "^https"){ 170 | $params.add('SkipCertificateCheck',$true) 171 | } 172 | if($credential){ 173 | $params.add('credential',$credential) 174 | $params.add('AllowUnencryptedAuthentication',$true) 175 | } 176 | 177 | } 178 | $Results = Invoke-RestMethod -Uri $Url @params 179 | 180 | 181 | if($Results.results.error){write-error $Results.results.error} 182 | else{ 183 | $measurement=$Results.results.series.name 184 | $columns=$Results.results.series.columns|select -unique 185 | $data = [System.Collections.ArrayList]@() 186 | if($Results.results.series.tags){ 187 | $tags=$Results.results.series[0].tags|select -unique 188 | $keys=get-variable -name t1|select -expand value|gm|?{$_.MemberType -eq "NoteProperty"}|select -expand name 189 | 190 | } 191 | 192 | foreach($s in $Results.results.series){ 193 | 194 | foreach($v in $s.values){ 195 | $item=@{} 196 | for ($i=0;$i -lt $columns.count;$i++){ 197 | if($columns[$i] -eq "time"){$item.add($columns[$i],[datetime]$v[$i]) } 198 | else{$item.add($columns[$i],$v[$i])} 199 | } 200 | if($tags){ 201 | if($keys.count -eq 1){$item.add($keys,$s.tags.$keys)} 202 | else{ 203 | for ($j=0;$j -lt $keys.count;$j++){ 204 | $item.add($keys[$j],$s.tags.$($keys[$j])) 205 | } 206 | } 207 | 208 | } 209 | $null = $data.add([pscustomobject]$item) 210 | } 211 | 212 | } 213 | return $data 214 | } 215 | } 216 | Function convertto-lineprotocol{ 217 | param( 218 | [string]$measurement, 219 | [pscustomobject]$data 220 | ) 221 | $d1=$data[0] 222 | $keys=get-variable -name d1|select -expand value|gm|?{$_.MemberType -eq "NoteProperty"}|select -expand name 223 | $series=[System.Collections.ArrayList]@() 224 | $measurement|write-host -fore cyan 225 | foreach($key in $keys){'{0} -> {1}'-f $key,$d1.$key.gettype().name|out-host} 226 | foreach($item in $data){ 227 | $tags=$values=@() 228 | foreach($key in $keys){ 229 | if($d1.$key.gettype().name -eq "String"){$tags+='{0}={1}' -f $key,$item.$key -replace ' ','\ '} 230 | elseif($d1.$key.gettype().name -in "Decimal","Int32","Int64","Double"){$values+='{0}={1}' -f $key,$item.$key -replace ',','.'} 231 | elseif($d1.$key.gettype().name -eq "DateTime"){$time=convertto-unixtime $item.$key} 232 | } 233 | $line='{0},{1} {2} {3}' -f $measurement,($tags -join ","),($values -join ","),$time 234 | $null=$series.add($line) 235 | } 236 | return $series 237 | } 238 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Mikel V 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Powershell Monitoring Examples/Citrix Xenapp/README.txt: -------------------------------------------------------------------------------- 1 | Download Citrix XenApp 7 PowerShell SDKs and install in computer/server that execute the scripts 2 | -------------------------------------------------------------------------------- /Powershell Monitoring Examples/Citrix Xenapp/XAmaintenance_template.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/micelshima/InfluxDB-Powershell-Module/e62a2e05352fa7e2582f009f409d3fa1780aa67b/Powershell Monitoring Examples/Citrix Xenapp/XAmaintenance_template.csv -------------------------------------------------------------------------------- /Powershell Monitoring Examples/Citrix Xenapp/citrix7servers2influxdb.ps1: -------------------------------------------------------------------------------- 1 | Function get-freespace($server) 2 | { 3 | $Disks = gwmi -computername $Server win32_logicaldisk -filter "drivetype=3" 4 | foreach ($Disk in $Disks|?{$_.deviceid -eq "C:"}){$freeGB=[math]::round($Disk.FreeSpace/1GB,2)} 5 | if(![bool]$freeGB){$freeGB=0} 6 | return $freeGB 7 | } 8 | Function get-pendingreboot($server) 9 | { 10 | $HKLM = 2147483650 11 | $pending="0i" 12 | $reg = gwmi -List -Namespace root\default -ComputerName $server | Where-Object {$_.Name -eq "StdRegProv"} 13 | if($reg.Enumkey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update").snames -contains "RebootRequired"){$pending="1i"} 14 | elseif($reg.Enumkey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing").snames -contains "RebootPending"){$pending="1i"} 15 | elseif($reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager","PendingFileRenameOperations").sValue){$pending="1i"} 16 | elseif($reg.GetStringValue($HKLM,"SOFTWARE\Wow6432Node\Sophos\AutoUpdate\UpdateStatus\VolatileFlags","RebootRequired").sValue){$pending="1i"} 17 | return $pending 18 | } 19 | Function get-sophoserr($server) 20 | { 21 | $err="0i" 22 | try{ 23 | $sophosfile=(gci "\\$server\C$\ProgramData\Sophos\AutoUpdate\Logs\ALUpdate*.log"|sort lastwritetime -desc|select fullname -first 1).fullname 24 | $filecontent=get-content($sophosfile)|select -last 15 25 | foreach($line in $filecontent|sort -desc) 26 | { 27 | #$line 28 | if($line -match 'Sending message:') 29 | { 30 | if ($line -match "Install.Failure"){$err="1i"} 31 | break 32 | } 33 | } 34 | #write-host $err -fore magenta 35 | } 36 | catch{$err="2i"} 37 | return $err 38 | }#fin sophoserr 39 | 40 | #cargo el snappin de CITRIX 41 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 42 | #cargo el snapin de Citrix 7 43 | asnp citrix* 44 | #cargo las funciones de influxdb 45 | import-module "$PSscriptroot\..\..\InfluxDB-Powershell-Module" 46 | 47 | #CITRIX LICENSES 48 | $citrixlicenses=get-brokersite|select -expand licensedsessionsactive 49 | $body="citrix7licenses,farm=XenApp7 licensesinuse=$citrixlicenses,totallicenses=540" 50 | $body 51 | write-influxDB "monitoringdb" $body 52 | #CITRIX SERVERS STATUS 53 | $templatewks=import-csv "$scriptPath\XAmaintenance_template.csv" -delimiter "`t" 54 | $XAsessions=get-brokersession -protocol HDX|select MachineName,sessionstate,appstate,protocol,SessionType,applicationsinuse,BrokeringUserName,ClientVersion,ConnectionMode,Clientaddress 55 | $XAServers=get-brokerdesktop|select CatalogName,DesktopGroupName,AssociatedUserUPNs,AgentVersion,InMaintenanceMode,LastConnectionFailure,LastDeregistrationTime,MachineInternalState,MachineName,Tags 56 | $XAServers|%{ 57 | $objserver=""|select servername,load,missingwk,maintenance,activesessions,inactivesessions,pendingreboot,sophoserr 58 | $machinename=$_.machinename 59 | $objserver.servername=$machinename.split('\')[1] 60 | $objserver.activesessions=($XAsessions|?{$_.machinename -eq $machinename -and $_.sessionstate -eq "Active"}|measure-object).count 61 | $objserver.inactivesessions=($XAsessions|?{$_.machinename -eq $machinename -and $_.sessionstate -eq "Disconnected"}|measure-object).count 62 | $objserver.pendingreboot=get-pendingreboot $objserver.servername 63 | $objserver.sophoserr=get-sophoserr $objserver.servername 64 | $freeGB=get-freespace $objserver.servername 65 | 66 | $servkerwks=$templatewks|?{$_.servername -eq $objserver.servername}|select -expand tag 67 | $maintenance=compare-object -referenceObject $servkerwks -DifferenceObject ($_|select -expand tags)|?{$_.sideindicator -eq "<="}|select -expand inputobject 68 | if ([bool]$maintenance) 69 | { 70 | if ($maintenance.count -eq $servkerwks.count){$objserver.maintenance="2i"} 71 | else{$objserver.maintenance="1i"} 72 | $objserver.missingwk=$maintenance -join ";" 73 | } 74 | else 75 | { 76 | $objserver.missingwk="-" 77 | $objserver.maintenance="0i" 78 | } 79 | if($_.InMaintenanceMode){$objserver.maintenance="3i"} 80 | $body="citrix7servers,farm=XenApp7,servername=$($objserver.servername),missingwk=$($objserver.missingwk) activesessions=$($objserver.activesessions),inactivesessions=$($objserver.inactivesessions),maintenance=$($objserver.maintenance),pendingreboot=$($objserver.pendingreboot),sophoserr=$($objserver.sophoserr),free=$freeGB" 81 | $body 82 | write-influxDB "monitoringdb" $body 83 | } 84 | #CITRIX CLIENT VERSIONS 85 | $xasessions|?{$_.clientversion}|select @{l='ver';e={$_.clientversion.split(".")[0]}}|group ver|%{ 86 | $body="citrix7versions,farm=XenApp7,version=$($_.name) count=$($_.count)i" 87 | $body 88 | write-influxDB "monitoringdb" $body 89 | } 90 | #CITRIX CLIENT SUBNETS 91 | $subnets=@{'vpn'=0;'lan'=0;'wan'=0} 92 | $xasessions|?{$_.Clientaddress}|%{ 93 | if ($_.Clientaddress -match "^10." -or $_.Clientaddress -match "^192.168." -or $_.Clientaddress -match "^192.151." -or $_.Clientaddress -match "^192.170."){$subnets.VPN++} 94 | elseif ($_.Clientaddress -match "^172.16."){$subnets.LAN++} 95 | elseif($_.Clientaddress.split(".")[0] -eq "172" -and [int]($_.Clientaddress.split(".")[1]) -gt 16){$subnets.VPN++} 96 | else{$subnets.WAN++} 97 | } 98 | $keys=$subnets|select -expand keys 99 | $values=$subnets|select -expand values 100 | For ($i=0;$i -lt $subnets.Count;$i++){ 101 | $body="citrix7subnets,farm=XenApp7,subnet=$($keys[$i]) count=$($values[$i])i" 102 | $body 103 | write-influxDB "monitoringdb" $body 104 | } 105 | #CITRIX APPLICATIONS 106 | $xasessions|?{$_.applicationsinuse}|select -expand applicationsinuse|group|%{ 107 | $body="citrix7apps,farm=XenApp7,app=$($_.name -replace('\\','/') -replace(' ','\ ')) count=$($_.count)i" 108 | $body 109 | write-influxDB "monitoringdb" $body 110 | } 111 | -------------------------------------------------------------------------------- /Powershell Monitoring Examples/DHCP/DHCP2influxdb.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/micelshima/InfluxDB-Powershell-Module/e62a2e05352fa7e2582f009f409d3fa1780aa67b/Powershell Monitoring Examples/DHCP/DHCP2influxdb.csv -------------------------------------------------------------------------------- /Powershell Monitoring Examples/DHCP/DHCP2influxdb.ps1: -------------------------------------------------------------------------------- 1 | #cargo las funciones de influxdb 2 | import-module "$PSscriptroot\..\..\InfluxDB-Powershell-Module" 3 | $content=import-csv "$Psscriptroot\DHCP2influxdb.csv" -delimiter "`t" 4 | foreach ($item in $content){ 5 | $skip=$false 6 | $failovercluster=get-dhcpserverv4failover -computername $item.server 7 | if ($failovercluster) 8 | { 9 | $server=$failovercluster.name 10 | if ($item.server -match "02$" -and $failovercluster.State -ne 'PartnerDown'){$skip=$true} 11 | } 12 | else{$server=$item.server.toupper()} 13 | if($skip -eq $false){ 14 | $result=Get-DhcpServerv4Statistics -computername $item.server 15 | $inuse = $result.AddressesInUse 16 | $free = $result.AddressesAvailable 17 | $total = $result.TotalAddresses 18 | $body="dhcpleases,location=$($item.location),servername=$server total=$total,free=$free,inuse=$inuse" 19 | $body 20 | write-influxDB "monitoringdb" $body 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Powershell Monitoring Examples/File Servers/clusterdrives.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/micelshima/InfluxDB-Powershell-Module/e62a2e05352fa7e2582f009f409d3fa1780aa67b/Powershell Monitoring Examples/File Servers/clusterdrives.csv -------------------------------------------------------------------------------- /Powershell Monitoring Examples/File Servers/drivestatus2influxdb.ps1: -------------------------------------------------------------------------------- 1 | #Monitor server drives 2 | #Mikel V 3 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 4 | #load influxdb functions 5 | import-module "$PSscriptroot\..\..\InfluxDB-Powershell-Module" 6 | #load file with drives to care about in the failover cluster 7 | $cluster=import-csv $scriptPath\clusterdrives.csv -delimiter "`t" 8 | $objFSO = New-Object -com Scripting.FileSystemObject 9 | $drives=gwmi Win32_logicalDisk -filter "drivetype=3" 10 | foreach($drive in $drives|?{($cluster|select -expand drive) -contains $_.deviceid}) 11 | { 12 | $clustername=($cluster|?{$_.drive -eq $Drive.deviceid}).server 13 | $sizeGB=[math]::round($Drive.Size/1GB,1) 14 | $freeGB=[math]::round($Drive.freespace/1GB,1) 15 | $oscysfolder="$($Drive.deviceid)\OSCYS" 16 | if (test-path $oscysfolder){$oscysSizeGB = [math]::round(($objFSO.GetFolder($oscysfolder).Size)/1GB,0)} 17 | else{$oscysSizeGB=0} 18 | $body="drivestatus,technology=3PAR,scope=NAC,location=Madrid,servername=$clustername,drive=$($Drive.deviceid) size=$sizeGB,free=$freeGB,oscys=$oscysSizeGB" 19 | $body 20 | write-influxDB "monitoringdb" $body 21 | } 22 | -------------------------------------------------------------------------------- /Powershell Monitoring Examples/File Servers/quotas(2012).ps1: -------------------------------------------------------------------------------- 1 | #Monitor quotas for history purposes with the help of FSRM module 2 | #Mikel V 3 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 4 | #load FSRM module (2012 R2) 5 | import-module FileServerResourceManager -ErrorAction Stop 6 | #load influxdb functions 7 | import-module "$PSscriptroot\..\..\InfluxDB-Powershell-Module" 8 | #load file with drives to care about in the failover cluster 9 | $info=import-csv "$scriptPath\clusterdrives.csv" -delimiter "`t" 10 | $hoy=get-date -uformat "%Y/%m/%d" 11 | $mes=get-date -uformat "%Y-%m" 12 | $servers="SERVER01A","SERVER01B" 13 | $quotas=get-fsrmquota -cimsession $servers 14 | foreach ($quota in $quotas) 15 | { 16 | $unidad=$quota.path.substring(0,2) 17 | $clfserver=($info|?{$_.drive -eq $unidad}).server 18 | $MBquota=[math]::truncate($quota.size/1MB) 19 | $MBused=[math]::truncate($quota.usage/1MB) 20 | $GBused=[math]::round($quota.usage/1GB,2) 21 | $path=$quota.path -replace("\\","/") 22 | $path=$path -replace(" ","\ ") 23 | out-file ".\logs\Quotas_$mes.csv" -input "$hoy;$unidad;$($quota.path);$MBquota;$MBused" -append 24 | $body="quotausage,technology=StorSimple,scope=NAC,location=Sarriguren,servername=$clfserver,path=$path used=$GBused" 25 | $body 26 | write-influxDB "historydb" $body 27 | } 28 | -------------------------------------------------------------------------------- /Powershell Monitoring Examples/File Servers/quotaswarnings2influxdb.ps1: -------------------------------------------------------------------------------- 1 | #Monitor quotas that are almost full with the help of FSRM module 2 | #Mikel V 3 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 4 | #load FSRM module (2012 R2) 5 | import-module FileServerResourceManager -ErrorAction Stop 6 | #load influxdb functions 7 | import-module "$PSscriptroot\..\..\InfluxDB-Powershell-Module" 8 | #load file with drives to care about in the failover cluster 9 | $cluster=import-csv $scriptPath\clusterdrives.csv -delimiter "`t" 10 | #load file of paths that I don't care about 11 | $castigados=get-content $scriptPath\LISTANEGRA.txt 12 | #this server 13 | $server=$env:computername.toupper() 14 | $watchout_limit=2 * 1073741824 #2GB 15 | $critical_limit=0.5 * 1073741824 #0,5GB 16 | $watchout_limitU=0.2 * 1073741824 #200 MB para carpetas de usuarios 17 | $critical_limitU=0.1 * 1073741824 #100 MB para carpetas de usuarios 18 | get-fsrmquota -cimsession $server|?{$_.Softlimit -eq $false -and ((($_.usage + $watchout_limit) -gt $_.size -and ($_.path.substring(0,1) -ne "N" -and $_.path -notmatch 'M:\\USUARIOS')) -or (($_.usage + $watchout_limitU) -gt $_.size -and ($_.path.substring(0,1) -eq "N" -or $_.path -match 'M:\\USUARIOS')))}|%{ 19 | if ((($_.usage + $critical_limit) -ge $_.size -and ($_.path.substring(0,1) -ne "N" -and $_.path -notmatch 'M:\\USUARIOS')) -or (($_.usage + $critical_limitU) -ge $_.size -and ($_.path.substring(0,1) -eq "N" -or $_.path -match 'M:\\USUARIOS'))){$warning="2i"}else{$warning="1i"} 20 | if ($castigados -contains $_.path){$warning="0i"} 21 | $sizeGB=[math]::round($_.Size/1GB,1) 22 | $usageGB=[math]::round($_.usage/1GB,1) 23 | $freeGB=[math]::round(($_.size - $_.usage)/1GB,1) 24 | $path=$_.path -replace("\\","/") 25 | $path=$path -replace(" ","\ ") 26 | $clustername=($cluster|?{$_.drive -eq $path.substring(0,2)}).server 27 | $body="quotausage,technology=StorSimple,scope=NAC,location=Sarriguren,servername=$clustername,path=$path quota=$sizeGB,used=$usageGB,free=$freeGB,warning=$warning" 28 | $body 29 | write-influxDB "monitoringdb" $body 30 | } 31 | -------------------------------------------------------------------------------- /Powershell Monitoring Examples/NTP Servers/NTPsync2influxdb.ps1: -------------------------------------------------------------------------------- 1 | #Monitor server time with w32tm command 2 | #Mikel V 3 | #load influxdb functions 4 | import-module "$PSscriptroot\..\..\InfluxDB-Powershell-Module" 5 | 6 | #servidores NTP a los que consultar la hora 7 | $ntpservers="servercendc02.sistemaswin.com,serverpnadc03.sistemaswin.com,serverpnadc04.sistemaswin.com,serverbpnadc05.sistemaswin.com" 8 | 9 | $result=w32tm /monitor /computers:$ntpservers 10 | #parseo el resultado 11 | $result|%{ 12 | if ($_ -match ":123") 13 | { 14 | $server= $_.split('[')[0].trim().split(".")[0] 15 | $server 16 | } 17 | elseif($_ -cmatch "NTP:") 18 | { 19 | $endpos= 20 | $secs=$_.substring(0,$_.indexof("s")).split(":")[1].trim() -replace('\+') 21 | $secs 22 | $body="ntpserverstime,servername=$server secs=$secs" 23 | $body 24 | write-influxDB "monitoringdb" $body 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Powershell Monitoring Examples/VMware vSphere/README.txt: -------------------------------------------------------------------------------- 1 | Download VMware vSphere PowerCLI and install in computer/server that execute the scripts -------------------------------------------------------------------------------- /Powershell Monitoring Examples/VMware vSphere/vmIOPS2influxdb.ps1: -------------------------------------------------------------------------------- 1 | #Check VM IOPS and write latency in VCenter 2 | #Mikel V 3 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 4 | #load powercli snappin 5 | if (!(Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) { 6 | Add-PSSnapin VMware.VimAutomation.Core 7 | } 8 | #cargo las funciones de influxdb 9 | import-module "$PSscriptroot\..\..\InfluxDB-Powershell-Module" 10 | $myVC = "servervc1.sistemaswin.com" 11 | $hostpwd='put here your root password encoded with key below' 12 | $hostcred = New-Object System.Management.Automation.PSCredential ("root", (ConvertTo-SecureString $hostpwd -key (1..16))) 13 | Set-PowerCLIConfiguration -DefaultVIServerMode Single -InvalidCertificateAction Ignore -Confirm:$false 14 | $VCServer = Connect-VIserver -server $myVC 15 | $vmhosts=get-vmhost|?{$_.connectionstate -eq "Connected" -and $_.Powerstate -eq "PoweredOn"}|select name 16 | Disconnect-VIServer -server $myVC -Confirm:$False 17 | foreach($vmhost in $vmhosts) 18 | { 19 | write-host $vmhost.name -fore cyan 20 | $HostServer = Connect-VIserver -server $vmhost.name -cred $hostcred 21 | $now=get-date 22 | $starttime=$now.addminutes(-60) 23 | $datastores=@() 24 | Get-Datastore|?{$_.Name -cmatch "^DS" -or $_.Name -cmatch "^3PARPNA0"}|select Name,id|sort name|%{ 25 | $ds=""|select name,id,wwn,type,cpd,entorno 26 | $ds.type="-" 27 | $ds.name=$_.name 28 | $ds.id=$_.id 29 | $ds.wwn=($_|get-view).Info.Vmfs.Extent[0].DiskName 30 | if ($ds.name -match "NL"){$ds.type="NL"} 31 | if ($ds.name -match "FC"){$ds.type="FC"} 32 | if ($ds.name -cmatch "_PPG"){$ds.type="PP"} 33 | if ($ds.name -cmatch "_RCG"){$ds.type="RC"} 34 | if ($ds.name -match "Sol" -or $ds.name -match "^3PARPNA02"){$ds.CPD="AS"}else{$ds.CPD="AE"} 35 | if ($ds.name -match "Ofimatica" -or $ds.name -match "_ESXOFI_"){$ds.entorno="Ofimatica"} 36 | if ($ds.name -match "Produccion" -or $ds.name -match "_ESXPRO_"){$ds.entorno="Produccion"} 37 | $datastores+=$ds 38 | }#fin foreach datastore 39 | write-host "Datastore Array collected" 40 | Get-VM -server $vmhost.name -erroraction silentlycontinue|?{$_.PowerState -eq "PoweredOn"}|%{ 41 | foreach($item in $_.datastoreIdlist) 42 | { 43 | $ds=$datastores|?{$_.id -eq $item} 44 | if ($ds -ne $null) 45 | { 46 | $iopsavg=$iopsmax=$latency=0 47 | $wval = Get-Stat $_ -stat "datastore.numberWriteAveraged.average" -Start $starttime -Finish $now -erroraction silentlycontinue|?{$item -match $_.instance} | select -expandproperty Value | measure -average -max 48 | $rval = Get-Stat $_ -stat "datastore.numberReadAveraged.average" -Start $starttime -Finish $now -erroraction silentlycontinue |?{$item -match $_.instance} | select -expandproperty Value | measure -average -max 49 | $lval = Get-Stat $_ -stat "disk.maxTotalLatency.latest" -Start $starttime -Finish $now | select -expandproperty Value | measure -max 50 | if ($wval -ne $null) 51 | { 52 | $iopsavg=[math]::round($rval.average + $wval.average,2) 53 | $iopsmax=[math]::round($rval.maximum + $wval.maximum,2) 54 | $latency=$lval.maximum 55 | $body="vmiops,datastore=$($ds.name),cpd=$($ds.cpd),entorno=$($ds.entorno),type=$($ds.type),host=$($vmhost.name),vm=$($_.name) iopsavg=$iopsavg,iopsmax=$iopsmax,latency=$($latency)i" 56 | $body 57 | write-influxDB "monitoringdb" $body 58 | } 59 | }#fin ds ne null 60 | }#fin datastoreidlist 61 | }#fin get-vm 62 | 63 | Disconnect-VIServer -server $vmhost.name -Confirm:$False 64 | }#fin hosts 65 | 66 | -------------------------------------------------------------------------------- /Powershell Monitoring Examples/VMware vSphere/vmcreationdeletion2influxdb.ps1: -------------------------------------------------------------------------------- 1 | #Check new VM's and deleted VM's in VCenter 2 | #Mikel V 3 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 4 | #load influxdb functions 5 | import-module "$PSscriptroot\..\..\InfluxDB-Powershell-Module" 6 | #load powercli snappin 7 | if (!(Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) { 8 | Add-PSSnapin VMware.VimAutomation.Core 9 | } 10 | $LastDays=60 11 | $VC="servervc1.sistemaswin.com" 12 | Set-PowerCLIConfiguration -DefaultVIServerMode Single -InvalidCertificateAction Ignore -Confirm:$false 13 | $VCServer = Connect-VIserver -server $VC 14 | 15 | $EventFilterSpecByTime = New-Object VMware.Vim.EventFilterSpecByTime 16 | If ($LastDays) 17 | { 18 | $EventFilterSpecByTime.BeginTime = (get-date).AddDays(-$LastDays) 19 | } 20 | $EventFilterSpec = New-Object VMware.Vim.EventFilterSpec 21 | $EventFilterSpec.Time = $EventFilterSpecByTime 22 | $EventFilterSpec.DisableFullMessage = $False 23 | $EventFilterSpec.Type = "VmCreatedEvent","VmDeployedEvent","VmClonedEvent","VmDiscoveredEvent","VmRegisteredEvent","VmRemovedEvent" 24 | $EventManager = Get-View EventManager 25 | $NewVmTasks = $EventManager.QueryEvents($EventFilterSpec) 26 | 27 | Foreach ($Task in $NewVmTasks) 28 | { 29 | $unixtime=convertto-unixtime $Task.CreatedTime 30 | $username=$Task.UserName -replace("\\","/") 31 | $servername=$Task.Vm.name 32 | $event="creation" 33 | if ($servername -match "_"){$n="0i"}else{$n="1i"} 34 | if ($Task -is [Vmware.vim.VmRemovedEvent]) 35 | { 36 | $event="deletion" 37 | $n="-$n" 38 | } 39 | $body="vmcreationdeletion,location=Sarriguren,vcenter=$VC,servername=$servername,username=$username,event=$event n=$n $unixtime" 40 | $body 41 | write-influxDB "reportingdb" $body 42 | } 43 | Disconnect-VIServer $VC -Confirm:$False 44 | -------------------------------------------------------------------------------- /Powershell Monitoring Examples/VMware vSphere/vmdatastores2influxdb.ps1: -------------------------------------------------------------------------------- 1 | #Check datastore usage in VCenter 2 | #Mikel V 3 | $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 4 | #load powercli snappin 5 | if (!(Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) { 6 | Add-PSSnapin VMware.VimAutomation.Core 7 | } 8 | #load influxdb functions 9 | import-module "$PSscriptroot\..\..\InfluxDB-Powershell-Module" 10 | $myVC = "servervc1.sistemaswin.com" 11 | Set-PowerCLIConfiguration -DefaultVIServerMode Single -InvalidCertificateAction Ignore -Confirm:$false 12 | $VCServer = Connect-VIserver -server $myVC 13 | Get-Datastore|?{$_.Name -cmatch "^DS" -or $_.Name -cmatch "^3PARPNA0"}| Sort Name|%{ 14 | 15 | $dsname=$_.name 16 | $sizeGB=[Math]::Round(($_.ExtensionData.Summary.Capacity)/1GB,0) 17 | 18 | $freeGB=[Math]::Round(($_.ExtensionData.Summary.freespace)/1GB,0) 19 | #reservation of 10% equals to Available storage 20 | $available=$_.ExtensionData.Summary.freespace -($_.ExtensionData.Summary.Capacity/10) 21 | $availableGB=[Math]::Round($available/1GB,0) 22 | $type=$CPD=$entorno="-" 23 | if ($dsname -match "NL"){$type="NL"} 24 | if ($dsname -match "FC"){$type="FC"} 25 | if ($dsname -cmatch "_PPG"){$type="PP"} 26 | if ($dsname -cmatch "_RCG"){$type="RC"} 27 | if ($dsname -match "Sol" -or $dsname -match "^3PARPNA02"){$CPD="AS"}else{$CPD="AE"} 28 | if ($dsname -match "Ofimatica" -or $dsname -match "_ESXOFI_"){$entorno="Ofimatica"} 29 | if ($dsname -match "Produccion" -or $dsname -match "_ESXPRO_"){$entorno="Produccion"} 30 | #write-host "$dsname $sizeGB $freeGB $availableGB" 31 | $body="vmdatastores,datastore=$dsname,cpd=$cpd,entorno=$entorno,type=$type size=$sizeGB,free=$freeGB,available=$availableGB" 32 | $body 33 | write-influxDB "monitoringdb" $body 34 | } 35 | Disconnect-VIServer $myVC -Confirm:$False 36 | -------------------------------------------------------------------------------- /Query2influxdb.ps1: -------------------------------------------------------------------------------- 1 | # InfluxDB query with Powershell 2 | # Mikel V. 29/12/2016 3 | #resize the window 4 | $pshost = get-host 5 | $pswindow = $pshost.ui.rawui 6 | $newsize = $pswindow.windowsize 7 | $bnewsize = $pswindow.buffersize 8 | $newsize.width = 150 9 | $newsize.height = 55 10 | $bnewsize.width=$newsize.width 11 | $pswindow.buffersize=$bnewsize 12 | $pswindow.windowsize = $newsize 13 | #####window resized###### 14 | write-host '' 15 | write-host ' 8888888 .d888 888 8888888b. 888888b. ' 16 | write-host ' 888 d88P" 888 888 "Y88b 888 "88b ' 17 | write-host ' 888 888 888 888 888 888 .88P ' 18 | write-host ' 888 88888b. 888888 888 888 888 888 888 888 888 8888888K. ' 19 | write-host ' 888 888 "88b 888 888 888 888 Y8bd8P 888 888 888 "Y88b' 20 | write-host ' 888 888 888 888 888 888 888 X88K 888 888 888 888' 21 | write-host ' 888 888 888 888 888 Y88b 888 .d8""8b. 888 .d88P 888 d88P' 22 | write-host ' 8888888 888 888 888 888 "Y88888 888 888 8888888P" 8888888P" ' 23 | write-host '' 24 | import-module "$PSscriptroot\InfluxDB-Powershell-Module" 25 | $raya= "-" * 40 26 | do 27 | { 28 | write-host "`nDATABASES" -fore cyan 29 | write-host $raya -fore cyan 30 | read-influxdb "_internal" "SHOW DATABASES"|?{$_.name}|%{write-host $_.name -fore cyan} 31 | $database=read-host "database" 32 | if ($database -ne 'exit') 33 | { 34 | do 35 | { 36 | write-host "`nMEASUREMENTS IN $($database.toupper())" -fore cyan 37 | write-host $raya -fore cyan 38 | $measurements=read-influxdb $database "SHOW MEASUREMENTS"|?{$_.name}|select -expand name 39 | $measurements|%{write-host $_ -fore cyan} 40 | $qry=read-host "InfluxQL query" 41 | if ($qry -ne 'exit') 42 | { 43 | if($qry -match "delete" -and $qry -notmatch "where"){write-host "NO BORRES TODA LA TABLA!!" -fore yellow} 44 | else{ 45 | if ($measurements -contains $qry){$qry="select * from $qry"} 46 | $object=read-influxdb $database $qry 47 | $object|ft * -auto 48 | } 49 | } 50 | }while($qry -ne "exit") 51 | } 52 | }while($database -ne "exit") 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # InfluxDB-Powershell-Module 2 | Powershell module to deal with InfluxDB. It requires powershell 3+ because it uses invoke-webrequest cmdlet. 3 | 4 | If you are using an earlier version you can use yukisagi's Invoke-HttpMethod function: 5 | https://github.com/yukiusagi2052/PowerShell-InfluxDB/blob/master/Invoke-InfluxWrite.ps1 6 | (I have been using it in all my powershell 2.0 servers and works like charm) 7 | 8 | I have also published my advanced monitoring scripts which are the collectors of these grafana dashboards: https://grafana.net/users/micelshima/dashboards 9 | 10 | For example: 11 | ![img tag](https://grafana.net/api/dashboards/1118/images/755/image) 12 | --------------------------------------------------------------------------------