Locality.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
function Get-Locality {
    <#
    .SYNOPSIS
    This cmdlet attempts to parse out locations from the input
 
    .DESCRIPTION
    By default, the cmdlet is loaded with many countries, all 50 US states, and some cities. You can extend or overwrite each of these lists.
 
    The cmdlet will then attempt to guess each state, country, land (larger than single country), area (something within a state), region (something within a country), and city.
 
    It will create an object and leave any unresolved text available for review
 
    Countries sourced from: https://www.nationsonline.org/oneworld/countries_of_the_world.htm
    States sourced from: https://abbreviations.yourdictionary.com/articles/state-abbrev.html
    Capitols sourced from: https://www.50states.com/tools/thelist.htm
    Largest Cities sourced from: https://www.mymove.com/city-guides/compare/largest-us-cities/
 
    .PARAMETER InputObject
    The string to parse
 
    .PARAMETER Overwrite
    A hashtable containing one or more of the following keys: lands,countries,regions,states,areas,cities. Will replace any inbuilt lists with the values found in each key.
 
    .PARAMETER Append
    A hashtable containing one or more of the following keys: lands,countries,regions,states,areas,cities. Will append to any inbuilt lists with the values found in each key.
 
    .EXAMPLE
    PS> "NYC" | Get-Locality
 
    Land :
    Country : United States
    Region :
    State : New York
    Area :
    City : New York City
    Unknown :
 
    .EXAMPLE
    PS> Get-Locality Reno
 
    Land :
    Country :
    Region :
    State :
    Area :
    City :
    Unknown : Reno
 
    This example shows what happens when a location is unknown
 
    .EXAMPLE
    PS> Get-Locality -Append @{cities=@{name="Reno"}} Reno
 
    Land :
    Country :
    Region :
    State :
    Area :
    City : Reno
    Unknown :
 
    This example shows how you can append a list of city hashtables to the cities list to recognize specific cities
 
    .EXAMPLE
    PS> Get-Locality -Append @{cities=@{name="Reno";state="Nevada"}} Reno
 
    Land :
    Country : United States
    Region :
    State : Nevada
    Area :
    City : Reno
    Unknown :
 
    This example shows how tying a city to a state allows the state to get resolved to a country
 
        .EXAMPLE
    PS> Get-Locality "Carson City"
 
    Land :
    Country : United States
    Region :
    State : Nevada
    Area :
    City : Carson City
    Unknown :
 
    This example showcases how any state capitol is a known city and can be resolved to larger geo units
 
    .EXAMPLE
    PS> Get-Locality "Carson City" -Overwrite @{cities=@{}}
 
    Land :
    Country :
    Region :
    State :
    Area :
    City :
    Unknown : Carson City
 
    This example shows how overriding the cities list can make inbuilt known locations no longer known.
 
    .EXAMPLE
    PS> "Phoenix,Arizona","Switzerland","Ghana,Accra","Central America","Phoenix,Arizona,USA","England","Pacific NorthWest","pnw","Austin","Georgia" | Get-Locality |ft -auto
 
    Land Country Region State Area City Unknown
    ---- ------- ------ ----- ---- ---- -------
                    United States Arizona Phoenix
                    Switzerland
                    Ghana Accra
    Central America
                    United States Arizona Phoenix
                    United Kingdom England
                    United States Pacific North West
                    United States Pacific North West
                    United States Texas Austin
                    United States Georgia
 
    This example shows how abbreviations are all converted to the same base name and how any known locations resolve to their larger known geographic units as well.
 
    .NOTES
    ### Known Issue ###
    Georgia sucks. We will always assume that the state of georgia is meant, not the country:
 
    PS> Get-Locality "Georgia","Tbilisi,Georgia","Atlanta,Georgia"| ft
 
    Land Country Region State Area City Unknown
    ---- ------- ------ ----- ---- ---- -------
         United States Georgia
         United States Georgia Tbilisi
         United States Georgia Atlanta
 
    If you are using Georgia the country, you'll need to use the local name or the name Georgia_Country like so:
 
    PS> Get-Locality "Georgia","Tbilisi,Sakartvelo","Tbilisi,Georgia_Country","Atlanta,Georgia"| ft
 
    Land Country Region State Area City Unknown
    ---- ------- ------ ----- ---- ---- -------
         United States Georgia
         Georgia_Country Tbilisi
         Georgia_Country Tbilisi
         United States Georgia Atlanta
 
    #>

    [cmdletbinding()]
    param(
        [Parameter(ValueFromPipeline, Mandatory)]
        $InputObject,
        [hashtable]$Overwrite,
        [hashtable]$Append
    )

    begin {
        # Dynamically load any existing json files to populate these lists
        "lands", "countries", "regions", "states", "areas", "cities" | ForEach-Object {
            # If runtime doesn't want to use the existing file (-Overwrite), use their param instead
            if ($PSBoundparameters.Overwrite.$_) {
                [array]$obj = $PSBoundparameters.Overwrite.$_
            }
            elseif (Test-Path $PSScriptRoot\$_.json) {
                [array]$obj = Get-ChildItem $PSScriptRoot\$_.json | ForEach-Object { Get-Content $_.Fullname } | ConvertFrom-Json
            }
            else {
                # At least need an array object to add to
                [array]$obj = @()
            }

            # If runtime wants to add extra items to the list, they should get added here
            if ($PSBoundparameters.Append.$_) {
                $obj += $PSBoundparameters.Append.$_
            }

            # Need to ensure that we have only 1 entry in the list with the same value in the property "name"
            # Needs to be case insensitive detection and needs to not get sorted
            $out = [ordered]@{}
            $obj | Where-Object { $_.Name } | ForEach-Object {
                if (-not $out.Contains($_.Name)) {
                    $out.Add($_.Name, [PSCustomObject]$_)
                }
            }

            Set-Variable -Name $_ -Value $out.values

            # Get any external modules or commands that should get executed before or after processing
            $script:modules = @(Get-Module).Where{ $_.PrivateData -and $_.PrivateData.ContainsKey("Locality") }
            if (-not [string]::IsNullOrWhiteSpace($Locality_Pre)) {
                $script:pre = $Locality_Pre
            }
            else {
                $script:pre = ""
            }
            if (-not [string]::IsNullOrWhiteSpace($Locality_Post)) {
                $script:post = $Locality_Post
            }
            else {
                $script:post = ""
            }
        }
    }
    process {
        foreach ($item in $InputObject) {
            $item = Invoke-Hook -HookType Pre -InputObject $item
            $item = [Locality]::New($item, $Lands, $Countries, $Regions, $States, $Areas, $Cities)
            $item = Invoke-Hook -HookType Post -InputObject $item
            $item
        }
    }
}
class Locality {
    [string]$Land
    [string]$Country
    [string]$Region
    [string]$State
    [string]$Area
    [string]$City
    [string]$Unknown
    hidden [System.Collections.Generic.List[string]]$Leftover

    Locality([string]$Location, $Lands, $Countries, $Regions, $States, $Areas, $Cities) {
        # Need to split the base string into some basic components
        $this.Leftover = ($Location.Trim() -split "[,;:|]+ *").Trim()

        # Prioritize country over state, state over area, etc.
        $SearchOrder = @(
            @{name = "Country"; variable = "Countries" }
            @{name = "State"; variable = "States" }
            @{name = "Area"; variable = "Areas" }
            @{name = "Land"; variable = "Lands" }
            @{name = "Region"; variable = "Regions" }
            @{name = "City"; variable = "Cities" }
        )
        foreach ($item in $SearchOrder) {
            $names = "Land", "Country", "Region", "State", "Area", "City"
            $obj = Get-Variable $item.variable -ValueOnly
            $name = $item.name

            # Search all properties in all objects in the list except for the properties that get assigned on match ($names)
            $properties = $obj |
            ForEach-Object { $_.PSObject.Properties.Name } |
            Select-Object -Unique |
            Where-Object { $_ -notin $names }
            Write-Verbose "Searching properties: $properties"

            foreach ($property in $properties) {
                if ($this.Leftover -and -not $this.$name) {
                    Write-Verbose "Listing $name - $property"
                    # Create match list of the unmatched properties
                    if ($results = $obj | Where-Object { $_.$property -match "^$($this.Leftover -join '$|^')$" }) {
                        $this.$name = $results.name | Select-Object -First 1
                        "Found ${name} (for property- $property): {0}" -f $this.$name | Write-Verbose
                        $this.RemoveLeftover(($results.$property | Select-Object -First 1))
                        # If match found, check the $names properties on that object and set other data on the output object accordingly
                        foreach ($name in $names) {
                            if ($results.$name -and -not $this.$name) {
                                $this.$name = $results.$name | Select-Object -First 1
                                "Found context ($name): {0}" -f $this.$name | Write-Verbose
                                $this.RemoveLeftover($this.$name)
                            }
                        }
                    }
                    elseif ($name -eq "State") {
                        # States often get added to a line without any separater (e.g. `Boston MA`, `Tala Fla.`, or `Des Moines Iowa`)
                        # If the line ends with any state matches, peel that state part off the line
                        if ($results = $obj | Where-Object { $this.Leftover -match " $($_.$property -join '$| ')$" }) {
                            $this.$name = $results.name
                            "Found ${name}: {0}" -f $this.$name | Write-Verbose
                            $item, $rest = $this.Leftover.Where({ $_ -match " $($Results.$property)$" }, "Split", 1)
                            $this.Leftover = $rest
                            $this.Leftover.Add(($item -replace " $($Results.$property)"))
                            $this.Leftover = $this.Leftover | Where-Object { $_ }
                        }
                    }
                }
            }
            # When searching for state,
            # Washingtonions say state to remove ambiguity with Wash DC.
            # Their state should always end up as just the state name
            if ($name -eq "State" -and $this.Leftover -like "Washington State") {
                $results = $this.Leftover -like "Washington State" | Select-Object -First 1
                $this.$name = "Washington"
                "Found state match {0}" -f $this.$name | Write-Verbose
                $this.RemoveLeftover($results)
            }
            # When searching for area,
            # If any lefover lines end in ` county`, call that an area and remove.
            elseif ($name -eq "Area" -and -not $this.$name) {
                if ($results = $this.Leftover | Where-Object { $_ -match " County$" }) {
                    $this.$name = $results | Select-Object -First 1
                    "Found fuzzy match ($name): {0}" -f $this.$name | Write-Verbose
                    $this.RemoveLeftover($this.$name)
                }
            }
        }

        # When state is good and there are still leftovers, assign the leftover to the area.
        if ($this.State -and $this.Leftover) {
            $item = $this.Leftover | Select-Object -First 1
            $this.Leftover.Remove($item)
            if ([string]::IsNullOrWhiteSpace($this.Area)) {
                $this.Area = $item
                "Found (fuzzy) Area: {0}" -f $this.Area | Write-Verbose
            }
            else {
                $this.Unknown = $item
                "Found (fuzzy) Unkown: {0}" -f $this.Unknown | Write-Verbose
            }
        }

        # After the base searching is all done, do another pass with cities, states, and countries
        # Try to add the larger locations if the more specific location is known
        $this.ResolveLocations($Countries, $States, $Cities)

        # Leftover isn't a pretty object on output (its a list, not an array)
        # So Leftover has been set to hidden
        # Unknown which is an array is output instead
        if ($this.Leftover) {
            if ([string]::IsNullOrWhiteSpace($this.Unknown)) {
                $this.Unknown = $this.Leftover -join ", "
            }
            else {
                $this.Unknown += ", " + ($this.Leftover -join ", ")
            }
        }
    }

    RemoveLeftover([string]$item) {
        # Create a scriptblock with a here-string that contains a here-string to protect against injection accidents
        $sb = @"
param(`$i)
`$i -eq @"
$item
`"@
"@

        $sb = [scriptblock]::Create($sb)

        # Arrays.Remove() methods are all case sensitive. But FindIndex with a scriptblock predicate can choose NOT to be.
        # Use FindIndex with the sb above to do a case insensitive search for the input $item and then remove it from the array.
        if (($index = $this.Leftover.FindIndex($sb)) -ne -1) {
            Write-Verbose "found index $index"
            $this.Leftover.RemoveAt($index)
        }
        else {
            Write-Verbose "found no index for item $item"
        }
    }

    ResolveLocations($Countries, $States, $Cities) {

        if ($this.City -and -not $this.State) {
            # Cities that have a known state can be assigned to that state.
            if ($result = $Cities | Where-Object { $_.Name -eq $this.City -and $_.State }) {
                $this.State = $result.State
            }
        }
        if ($this.State -and -not $this.Country) {
            # States that have a known country can be assigned to that country.
            if ($result = $States | Where-Object { $_.Name -eq $this.State -and $_.Country }) {
                $this.Country = $result.Country
            }
        }
    }

    [string] ToString() {
        $output = ""
        @(
            "Unknown"
            "City"
            "Area"
            "State"
            "Region"
            "Country"
            "Land"
        ) | ForEach-Object {
            if (-not [string]::IsNullOrWhiteSpace($this.$_)) {
                $output += ", " + $this.$_
            }
        }
        return $output.Trim(', ')
    }
}
function Invoke-Hook {
    # This function has two parts: Processing to do if there are module hooks and processing for a command hook
    [CmdletBinding()]
    param(
        [ValidateSet("Pre", "Post")]
        [Parameter(Mandatory)]
        [string]$HookType,

        $InputObject
    )

    # Part one: Module Hooks
    foreach ($mi in $script:modules) {
        try {
            # Only run if the hashtable pre/post properties exist and are set with actual text
            if (-not [string]::IsNullOrWhiteSpace($mi.PrivateData["Locality"][$HookType])) {
                Write-Verbose "Executing command $($mi.Name)\$($mi.PrivateData["Locality"][$HookType]) with data $InputObject"
                $InputObject = & "$($mi.Name)\$($mi.PrivateData["Locality"][$HookType])" $InputObject
            }
        }
        catch {
            Write-Warning "Failed to execute command '$($mi.Name)\$($mi.PrivateData["Locality"][$HookType])' with data $InputObject"
        }
    }

    # Part two: Command Hook
    # Need to use an if/else because script scope with dynamic text seems hard ($script:$HookType)
    if ($HookType -eq "Pre") {
        $command = $script:Pre
    }
    else {
        $command = $script:Post
    }
    # Don't need to validate -not [string]::IsNullOrWhiteSpace here because we already did that in the Begin block of the public function
    if ($command) {
        Write-Verbose "Executing command $command with data $InputObject"
        $InputObject = & $command -InputObject $InputObject
    }

    # Part three: Push data to the output stream
    $InputObject
}