-
Notifications
You must be signed in to change notification settings - Fork 1
/
main dict function.ps1
97 lines (79 loc) · 3.01 KB
/
main dict function.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
95
96
@'
see:
- https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_intrinsic_members?view=powershell-7.3
- https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-pscustomobject?view=powershell-7.4#using-defaultpropertyset-the-long-way
example removing
$myObject.psobject.properties.remove('ID')
'@
# function Get-MyObject
# {
# [OutputType('My.Object')]
# [CmdletBinding()]
# param
# (
# ...
# https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_intrinsic_members?view=powershell-7.3
function asDict {
<#
.SYNOPSIS
Converts PSObjects to hashtables
.EXAMPLE
#ps | s -First 2 | fl -Force *
ps | Select -first 3 | asDict -ExcludePropertyRegex '.*' -IncludePropertyRegex 'name', '64' -AsNewObject
#>
# [Alias('b.asDict')]
[CmdletBinding()]
[OutputType('System.Hashtable')]
param(
[Parameter(ValueFromPipeline, mandatory)]
[object[]]$InputObject,
# include property regex overrides any exlucded properties
[string[]]$IncludePropertyRegex, # overrides exclusion
# blacklist pattern regex
[string[]]$ExcludePropertyRegex,
[Alias('AsNewObject')]
[switch]$PassThru,
# should I explicit sort, or use ordered hashtable?
[switch]$NoSortKeys
)
process {
foreach ($Object in $InputObject) {
$target = $Object
if ($NoSortKeys) {
$possible_names = $target.psobject.properties.name
$props = @{}
}
else {
$possible_names = $target.psobject.properties.name | Sort-Object
$props = [ordered]@{}
}
foreach ( $curPropName in $possible_names) {
# blacklist filter
$shouldExclude = $false
foreach ($regex in $ExcludePropertyRegex) {
if ($CurPropName -match $regex) {
$ShouldExclude = $true
}
}
# override blacklist
foreach ($regex in $IncludePropertyRegex) {
if ($CurPropName -match $regex) {
$ShouldExclude = $false
}
}
if (-not $shouldExclude) {
$props[$curPropName] = $target.$curPropName
}
}
if ($PassThru) {
return [pscustomobject]$Props
}
$Props
}
}
}
Get-Item . | asDict -ExcludePropertyRegex 'link', 'name', 'date', 'time', 'path', '.*' -IncludePropertyRegex 'name'
#ps | s -First 2 | fl -Force *
Get-Process | Select-Object -First 3 | asDict -ExcludePropertyRegex '.*' -IncludePropertyRegex 'name', '64'
#ps | s -First 2 | fl -Force *
Get-Process | Select-Object -First 3 | asDict -ExcludePropertyRegex '.*' -IncludePropertyRegex 'name', '64' -AsNewObject