forked from dindenver/Backup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UpdateObjectExample.ps1
91 lines (82 loc) · 3.71 KB
/
UpdateObjectExample.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
#
# These examples show how to define a set of functions for manipulating
# a "database" of information about comic book characters
#
# Define the basic database
$characterData = @{
"Linus" = @{ age = 8; human = $true}
"Lucy" = @{ age = 8; human = $true}
"Snoopy" = @{ age = 2; human = $true}
}
#
# A function to get information about a character using
# pattern matching on the characters name
#
function Get-Character ($name = "*")
{
foreach ($entry in $characterData.GetEnumerator() | Write-Object)
{
if ($entry.Key -like $name)
{
$properties = @{ "Name" = $entry.Key } +
$entry.Value
New-Object PSCustomObject -Property $properties
}
}
}
#
# A function to set character information
# using objects read from the input pipe
#
function Set-Character {
process {
$characterData[$_.name] =
@{
age = $_.age
human = $_.human
}
}
}
function Update-Character (
[string] $name = '*',
[int] $age,
[bool] $human
)
{
begin
{
if ($PSBoundParameters."name")
{
$name = $PSBoundParameters.name
[void] $PSBoundParameters.Remove("name")
}
}
process
{
if ($_.name -like $name)
{
foreach ($p in $PSBoundParameters.GetEnumerator())
{
$_.($p.Key) = $p.value
}
}
$_
}
}
#
# Some examples showing how these functions would be used.
#
Get-Character | Format-Table -auto
Get-Character |
Update-Character -name snoopy -human $false |
Format-Table -auto
Get-Character | Format-Table -auto
Get-Character |
Update-Character -name snoopy -human $false |
Set-Character
Get-Character | Format-Table -auto
Get-Character L* | Format-Table -auto
Get-Character Linus |
Update-Character -age 7 |
Set-Character
Get-Character | Format-Table -auto