forked from jdhitsolutions/MemoryTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MemoryTools.psm1
527 lines (447 loc) · 15.3 KB
/
MemoryTools.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
#requires -version 4.0
#region Define functions
Function Get-MemoryUsage {
[cmdletbinding(DefaultParameterSetName='ComputernameSet')]
Param(
[Parameter(
Position = 0,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
ParameterSetName='ComputernameSet'
)]
[ValidateNotNullorEmpty()]
[Alias("cn")]
[string[]]$Computername = $env:Computername,
[ValidateSet("All","OK","Warning","Critical")]
[string]$Status = "All",
[Parameter(ParameterSetName='CimInstanceSessionSet', Mandatory, ValueFromPipeline)]
[ValidateNotNullorEmpty()]
[Microsoft.Management.Infrastructure.CimSession[]]$CimSession
)
Begin {
Write-Verbose "Starting: $($MyInvocation.Mycommand)"
Write-Verbose "PSBoundParameters"
Write-Verbose ($PSBoundParameters | Out-String)
$MyCimSession=@()
} #begin
Process {
Write-Verbose "Using parameter set $($PSCmdlet.ParameterSetName)"
if ($pscmdlet.ParameterSetName -eq 'ComputerNameSet') {
#create a temporary cimsession if using a computername
foreach ($item in $Computername) {
Try {
Write-Verbose "Creating temporary CIM Session to $item"
$MyCIMSession += New-CimSession -ComputerName $item -ErrorAction Stop -OutVariable +tmpSess
Write-Verbose "Added session"
}
Catch {
Write-Error "[$($item.toUpper())] Failed to create temporary CIM Session. $($_.exception.message)"
}
} #foreach item in computername
} #if computername parameter set
else {
Write-Verbose "Re-using CimSessions"
$MyCimSession = $CimSession
}
foreach ($session in $MyCIMSession) {
Write-Verbose "Processing $($session.computername)"
Try {
$os = Get-CimInstance -classname Win32_OperatingSystem -CimSession $session -ErrorAction stop
}
Catch {
Write-Error "[$($session.Computername.toUpper())] Failed to retrieve data. $($_.exception.message)"
}
if ($os) {
$pctFree = [math]::Round(($os.FreePhysicalMemory/$os.TotalVisibleMemorySize)*100,2)
if ($pctFree -ge $MemoryToolsOK) {
$StatusProperty = "OK"
}
elseif ($pctFree -ge $MemoryToolsWarning ) {
$StatusProperty = "Warning"
}
else {
#anything else is considered critical
$StatusProperty = "Critical"
}
$obj = $os | Select @{Name="Computername";Expression={ $_.PSComputername.toUpper()}},
@{Name = "Status";Expression = {$StatusProperty}},
@{Name = "PctFree"; Expression = {$pctFree}},
@{Name = "FreeGB";Expression = {[math]::Round($_.FreePhysicalMemory/1mb,2)}},
@{Name = "TotalGB";Expression = {[int]($_.TotalVisibleMemorySize/1mb)}}
#add a custom type name
$obj.psobject.typenames.insert(0,"MyMemoryUsage")
#write object to the pipeline
if ($Status -eq 'All') {
$obj
}
else {
#write filtered results
$obj | Where {$_.Status -match $Status}
}
#reset variables just in case
Clear-Variable OS,obj,Mycimsession
} #if OS
} #foreach
#clean up
if ($tmpSess) {
Write-Verbose "Removing temporary sessions"
$tmpSess | Remove-CimSession
remove-Variable tmpsess
}
} #process
End {
Write-Verbose "Ending: $($MyInvocation.Mycommand)"
} #end
} #end Get-MemoryUsage
Function Show-MemoryUsage {
[cmdletbinding(DefaultParameterSetName='ComputernameSet')]
Param(
[Parameter(
Position = 0,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
ParameterSetName='ComputernameSet'
)]
[ValidateNotNullorEmpty()]
[Alias("cn")]
[string[]]$Computername = $env:Computername,
[Parameter(ParameterSetName='CimInstanceSessionSet', Mandatory, ValueFromPipeline)]
[ValidateNotNullorEmpty()]
[Microsoft.Management.Infrastructure.CimSession[]]$CimSession
)
Begin {
Write-Verbose "Starting: $($MyInvocation.Mycommand)"
Write-Verbose "PSBoundParameters"
Write-Verbose ($PSBoundParameters | Out-String)
#a formatted report title
$title = @"
****************
* Memory Check *
****************
"@
Write-Host $title -foregroundColor Cyan
#initialize an array to hold data
$data = @()
} #begin
Process {
Write-Verbose "Using parameter set $($PSCmdlet.ParameterSetName)"
if ($pscmdlet.ParameterSetName -eq 'ComputerNameSet') {
foreach ($Computer in $Computername) {
#get memory usage data for each computer
$data += Get-MemoryUsage -Computername $computer
}
}
else {
foreach ($session in $CIMSession) {
#get memory usage data for each computer
$data += Get-MemoryUsage -CimSession $session
}
}
} #Process
End {
#write results to the host
#create a text table and split into an array based on each line
$strings = ($data | Format-Table | Out-String).Trim().split("`n")
#display the first two lines which should be the header
$strings | select -first 2 | write-host -ForegroundColor Cyan
#process remaining lines
$strings | select -Skip 2 | foreach {
#check for the status and select an appropriate color
Switch -regex ($_) {
"OK" { $color = "Green" }
"Warning" { $color = "Yellow" }
"Critical" {$color = "Red" }
}
#write the line with the corresponding alert color
Write-Host $_ -ForegroundColor $color
} #foreach string
#write an extra blank line
write-Host "`n"
Write-Verbose "Ending: $($MyInvocation.Mycommand)"
} #end
} #end Show-MemoryUsage
Function Test-MemoryUsage {
#get-memory usage and test for a minimum %free, FreeGB, TotalGB or UsedGB
[cmdletbinding(DefaultParameterSetName='PercentComputer')]
Param(
[ValidateNotNullorEmpty()]
[Alias("cn")]
[Parameter(Position=0,ValueFromPipeline,ValueFromPipelineByPropertyName,ParameterSetName="PercentComputer")]
[Parameter(Position=0,ValueFromPipeline,ValueFromPipelineByPropertyName,ParameterSetName="FreeComputer")]
[Parameter(Position=0,ValueFromPipeline,ValueFromPipelineByPropertyName,ParameterSetName="TotalComputer")]
[Parameter(Position=0,ValueFromPipeline,ValueFromPipelineByPropertyName,ParameterSetName="UsedComputer")]
[string[]]$Computername = $env:Computername,
[Parameter(Mandatory,ParameterSetName="PercentCIM")]
[Parameter(Mandatory,ParameterSetName="FreeCIM")]
[Parameter(Mandatory,ParameterSetName="TotalCIM")]
[Parameter(Mandatory,ParameterSetName="UsedCIM")]
[Microsoft.Management.Infrastructure.CimSession[]]$CimSession,
[Parameter(HelpMessage = "Enter the minimum % free memory",ParameterSetName="PercentComputer")]
[Parameter(HelpMessage = "Enter the minimum % free memory",ParameterSetName="PercentCIM")]
[ValidateNotNullorEmpty()]
[int]$PercentFree = 50,
[Parameter(HelpMessage = "Enter the minimum free memory in GB",Mandatory,ParameterSetName="FreeComputer")]
[Parameter(HelpMessage = "Enter the minimum free memory in GB",Mandatory,ParameterSetName="FreeCIM")]
[ValidateNotNullorEmpty()]
[double]$FreeGB,
[ValidateNotNullorEmpty()]
[Parameter(HelpMessage = "Enter the minimum total memory in GB",Mandatory,ParameterSetName="TotalComputer")]
[Parameter(HelpMessage = "Enter the minimum total memory in GB",Mandatory,ParameterSetName="TotalCIM")]
[int]$TotalGB,
[Parameter(HelpMessage = "Enter the minimum amount of used memory in GB",Mandatory,ParameterSetName="UsedComputer")]
[Parameter(HelpMessage = "Enter the manimum amount of used memory in GB",Mandatory,ParameterSetName="UsedCIM")]
[ValidateNotNullorEmpty()]
[double]$UsedGB,
[switch]$Quiet
)
Begin {
Write-Verbose "Starting: $($MyInvocation.Mycommand)"
Write-Verbose "PSBoundParameters"
Write-Verbose ($PSBoundParameters | Out-String)
} #begin
Process {
if ($Computername) {
$usage = foreach ($Computer in $Computername) {
#get memory usage data for each computer
Get-MemoryUsage -Computername $computer
}
}
else {
$usage = foreach ($session in $CIMSession) {
#get memory usage data for each computer
Get-MemoryUsage -CimSession $session -ErrorAction
}
}
Foreach ($mem in $usage) {
Switch -regex ($PSCmdlet.ParameterSetName) {
"Used" {
Write-Verbose "Testing if Used GB is >= to $UsedGB"
$used = $mem.TotalGB - $mem.FreeGB
Write-Verbose "Used = $used"
if ($Used -ge $usedGB) {
$Test = $True
}
else {
$Test = $False
}
$data = $mem | Select Computername,@{Name="UsedGB";Expression={$used}},
@{Name="Test";Expression={$test}}
}
"Total" {
Write-Verbose "Testing if Total size is >= $TotalGB"
if ($mem.TotalGB -ge $TotalGB) {
$Test = $True
}
else {
$Test = $False
}
$data = $mem | Select Computername,TotalGB,@{Name="Test";Expression={$test}}
}
"Free" {
Write-Verbose "Testing if Free GB is >= $FreeGB"
if ($FreeGB -le $mem.FreeGB) {
$Test = $True
}
else {
$Test = $False
}
$data = $mem | Select Computername,FreeGB,@{Name="Test";Expression={$test}}
}
"Percent" {
Write-Verbose "Testing if Percent free is >= $PercentFree"
if ($mem.PctFree -ge $percentFree) {
$Test = $True
}
else {
$Test = $False
}
$data = $mem | Select Computername,PctFree,@{Name="Test";Expression={$test}}
}
} #switch
if ($Quiet) {
$Test
}
else {
$data
}
} #foreach $mem
} #process
End {
Write-Verbose "[END ] Ending: $($MyInvocation.Mycommand)"
} #end
} #end Test-MemoryUsage
Function Get-MemoryPerformance {
[cmdletbinding()]
Param(
[Parameter(
Position = 0,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
ParameterSetName='ComputernameSet'
)]
[ValidateNotNullorEmpty()]
[Alias("cn")]
[string[]]$Computername = $env:Computername,
[Parameter(
ParameterSetName='CimInstanceSessionSet',
Mandatory,
ValueFromPipeline
)]
[ValidateNotNullorEmpty()]
[Microsoft.Management.Infrastructure.CimSession[]]$CimSession
)
Begin {
Write-Verbose "Starting: $($MyInvocation.Mycommand)"
<#
Get all memory performance counters. Assuming counters on the
client are the same as on the server. Sort by name.
#>
$all = (get-counter -ListSet Memory*).counter | Sort-Object
#get a list of class properties. Some of the properties don't
#appear to have any values and are different than what you get
#with Get-Counter
$perfclass = get-cimclass Win32_PerfFormattedData_PerfOS_Memory
$selected = $perfclass.CimClassProperties | select -Skip 9 -expandProperty Name
$selected+= @{Name="DateTime";Expression = {(Get-Date)}}
$selected+= @{Name="ComputerName";Expression={$session.ComputerName }}
Write-Verbose "PSBoundParameters"
Write-Verbose ($PSBoundParameters | Out-String)
} #begin
Process {
Write-Verbose "Using parameter set $($PSCmdlet.ParameterSetName)"
if ($pscmdlet.ParameterSetName -eq 'ComputerNameSet') {
#create a temporary cimsession if using a computername
$MyCIMSession = foreach ($item in $Computername) {
Try {
Write-Verbose "Creating temporary CIM Session to $item"
New-CimSession -ComputerName $item -ErrorAction Stop -OutVariable +tmpSess
Write-Verbose "Added session"
}
Catch {
Write-Error "[$($item.toUpper())] Failed to create temporary CIM Session. $($_.exception.message)"
}
} #foreach item in computername
} #if computername parameter set
else {
Write-Verbose "Re-using CimSessions"
$MyCimSession = $CimSession
}
foreach ($session in $MyCIMSession) {
Try {
Get-CimInstance -classname Win32_PerfFormattedData_PerfOS_Memory -CimSession $session |
Select-Object -property $selected
} #try
Catch {
Write-Error "Failed to get performance data from $($session.computername.toupper()). $($_.exception.message)"
}
} #foreach
#clean up
if ($tmpSess) {
Write-Verbose "Removing temporary sessions"
$tmpSess | Remove-CimSession
remove-Variable tmpsess
}
} #process
End {
Write-Verbose "[END ] Ending: $($MyInvocation.Mycommand)"
} #end
} #end Get-MemoryPerformance
Function Get-PhysicalMemory {
[cmdletbinding(DefaultParameterSetName="ComputerNameSet")]
Param(
[Parameter(
Position = 0,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
ParameterSetName='ComputernameSet'
)]
[ValidateNotNullorEmpty()]
[Alias("cn")]
[string[]]$Computername = $env:Computername,
[Parameter(
ParameterSetName='CimInstanceSessionSet',
Mandatory,
ValueFromPipeline
)]
[ValidateNotNullorEmpty()]
[Microsoft.Management.Infrastructure.CimSession[]]$CimSession
)
Begin {
Write-Verbose "Starting: $($MyInvocation.Mycommand)"
Write-Verbose "PSBoundParameters"
Write-Verbose ($PSBoundParameters | Out-String)
#define a hash table to resolve Form factor
$form = @{
0 = 'Unknown'
1 = 'Other'
2 = 'SIP'
3 = 'DIP'
4 = 'ZIP'
5 = 'SOJ'
6 = 'Proprietary'
7 = 'SIMM'
8 = 'DIMM'
9 = 'TSOP'
10 ='PGA'
11 = 'RIMM'
12 = 'SODIMM'
13 = 'SRIMM'
14 = 'SMD'
15 = 'SSMP'
16 = 'QFP'
17 = 'TQFP'
18 = 'SOIC'
19 = 'LCC'
20 = 'PLCC'
21 = 'BGA'
22 = 'FPBGA'
23 = 'LGA'
}
} #begin
Process {
Write-Verbose "Using parameter set $($PSCmdlet.ParameterSetName)"
if ($pscmdlet.ParameterSetName -eq 'ComputerNameSet') {
#create a temporary cimsession if using a computername
$MyCIMSession = foreach ($item in $Computername) {
Try {
Write-Verbose "Creating temporary CIM Session to $item"
New-CimSession -ComputerName $item -ErrorAction Stop -OutVariable +tmpSess
Write-Verbose "Added session"
}
Catch {
Write-Error "[$($item.toUpper())] Failed to create temporary CIM Session. $($_.exception.message)"
}
} #foreach item in computername
} #if computername parameter set
else {
Write-Verbose "Re-using CimSessions"
$MyCimSession = $CimSession
}
foreach ($session in $MyCIMSession) {
Write-Verbose "Processing $($session.computername)"
Try {
Get-CimInstance win32_physicalmemory -cimsession $session |
Select @{Name="Computername";Expression={$_.PSComputername.ToUpper()}},
Manufacturer,@{Name="CapacityGB";Expression={$_.Capacity/1GB}},
@{Name="Form";Expression={$form.item($_.FormFactor -as [int])}},
@{Name="ClockSpeed";Expression={$_.ConfiguredClockSpeed}},
@{Name="Voltage";Expression={$_.ConfiguredVoltage}},DeviceLocator
} #Try
Catch {
Write-Error "[$($Computer.toUpper())] $($_.exception.message)"
}
} #foreach
#clean up
if ($tmpSess) {
Write-Verbose "Removing temporary sessions"
$tmpSess | Remove-CimSession
remove-Variable tmpsess
}
} #process
End {
Write-Verbose "[END ] Ending: $($MyInvocation.Mycommand)"
} #end
} #get-PhysicalMemory
#endregion
#import module variables and aliases
. $PSScriptRoot\MemoryToolsSettings.ps1