-
Notifications
You must be signed in to change notification settings - Fork 0
/
V16 Advanced-Functions.ps1
94 lines (75 loc) · 2.59 KB
/
V16 Advanced-Functions.ps1
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
# help
Get-Help about_Functions_Advanced
# syntax
function Test-Function {
[CmdletBinding()]
#[CmdletBinding(SupportShouldProcess=$true)] unlocks parameters -Whatis and -Confirm
#[CmdletBinding(SupportPaging=$true)] unlocks parameters like -First, -Skip, and -IncludeTotalCount parameters
param
(
[Parameter(Mandatory=$true)]
$ComputerName
)
Begin {} # Optional, happens once, used for tasks such connecting to a database, of defining variables
process {} # Mandataroy, runs once for each object piped into the function
end {} # Optional, cleanup or disconnect from a database, etc..
}
# simple function
function Get-BootTimesSimple {
param(
[string[]]$ComputerName
)
$result = @()
foreach($computer in $ComputerName){
$os = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computer
[PSCustomObject]$stats = @{
ComputerName = $computer
LastBoot = $os.LastBootUpTime
UpTime = (Get-Date) - $os.LastBootUpTime
}
$result += $stats
}
$result |
Select-Object ComputerName, LastBoot, Uptime |
Sort-Object LastBoot -Descending
}
Get-BootTimesSimple -ComputerName 'DC1','DC2','Client1'
# advanced function
function Get-BootTimesAdvanced {
[CmdletBinding()]
param(
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string[]]$ComputerName
)
# optional pre-processing block (initialization)
begin {
$result = @()
}
# mandatory processing block (executes for each object in pipeline)
process {
foreach($computer in $ComputerName){
$os = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computer
[PSCustomObject]$boot = @{
ComputerName = $computer
LastBoot = $os.LastBootUpTime
UpTime = (Get-Date) - $os.LastBootUpTime
}
$result += $boot
}
}
# optional post-processing block (cleanup)
end {
$result |
Select-Object ComputerName, LastBoot, Uptime |
Sort-Object LastBoot -Descending
}
}
# usage
'DC1','DC2' | Get-BootTimesAdvanced
Get-BootTimesAdvanced 'Client1'
Get-BootTimesAdvanced -ComputerName 'DC1','DC2'
Get-ADComputer -Filter * | Select-Object -ExpandProperty Name | Get-BootTimesAdvanced