From d504ba1d7d39098ebbffcb54e6443b5ce884433e Mon Sep 17 00:00:00 2001 From: Mike Madeja Date: Sat, 7 Nov 2026 07:01:19 -0600 Subject: [PATCH 1/5] refactor: route API calls through Invoke-PiHoleApiRequest and add ShouldProcess Move every authenticated public function onto the shared request helper (74 of 77; Get-PiHoleAuthStatus, Get-PiHoleInfoClient and Get-PiHoleInfoLogin call endpoints that work without logging in). This removes the login/logout boilerplate from each file and fixes a few behaviours along the way: - Functions that look something up first (New-PiHoleGroup, Get-PiHoleDomain, ...) no longer hold an extra session open while the lookup logs in with its own. - A failed login stops with one error, instead of also sending the request without a session and reporting a second 401. - All catch blocks use ConvertTo-PiHoleFriendlyErrorMessage, so Pi-hole's own error message and hint come through instead of just the HTTP status. The helper gains pass-through Body, Form and OutFile parameters so the teleporter upload/download and query-string Get bodies fit unchanged. Add SupportsShouldProcess to the 16 state-changing functions that lacked it, so all 27 now accept -WhatIf and -Confirm. The API call sits inside the ShouldProcess check, so -WhatIf no longer logs in (gravity used to). ConfirmImpact stays at the default Medium, so nothing prompts unless the caller asks. Add-PiHoleDnsRecord passes -Confirm:$false to Add-PiHoleConfigArrayItem, matching Remove-PiHoleDnsRecord. Co-Authored-By: Claude Opus 5.5 --- .github/CONTRIBUTING.md | 9 +- .../Private/Invoke-PiHoleApiRequest.ps1 | 27 +++- .../Public/Actions/Invoke-PiHoleFlushLogs.ps1 | 39 ++--- .../Actions/Invoke-PiHoleFlushNetwork.ps1 | 39 ++--- .../Actions/Restart-PiHoleDnsService.ps1 | 39 ++--- .../Actions/Update-PiHoleActionsGravity.ps1 | 20 +-- .../Authentication/Get-PiHoleAuthStatus.ps1 | 2 +- .../Authentication/Get-PiHoleAuthTotp.ps1 | 20 +-- .../Get-PiHoleCurrentAuthSession.ps1 | 20 +-- .../Remove-PiHoleAuthSession.ps1 | 38 ++--- .../Authentication/Request-PiHoleAuth.ps1 | 2 +- .../ClientManagement/Get-PiHoleClient.ps1 | 24 +-- .../Get-PiHoleClientSuggestion.ps1 | 20 +-- .../ClientManagement/New-PiHoleClient.ps1 | 103 ++++++------- .../ClientManagement/Remove-PiHoleClient.ps1 | 24 +-- .../ClientManagement/Update-PiHoleClient.ps1 | 113 +++++++------- .../Config/Add-PiHoleConfigArrayItem.ps1 | 53 +++---- .../Public/Config/Get-PiHoleConfig.ps1 | 26 +--- .../Config/Get-PiHoleConfigProperty.ps1 | 20 +-- .../Config/Remove-PiHoleConfigArrayItem.ps1 | 22 +-- .../Public/Config/Set-PiHoleConfig.ps1 | 65 ++++---- .../Public/DHCP/Get-PiHoleDhcpLease.ps1 | 20 +-- .../Public/DHCP/Remove-PiHoleDhcpLease.ps1 | 20 +-- .../Public/DnsControl/Add-PiHoleDnsRecord.ps1 | 58 +++---- .../Get-PiHoleDnsBlockingStatus.ps1 | 20 +-- .../Public/DnsControl/Get-PiHoleDnsRecord.ps1 | 2 +- .../DnsControl/Remove-PiHoleDnsRecord.ps1 | 2 +- .../DnsControl/Set-PiHoleDnsBlocking.ps1 | 63 ++++---- .../DomainManagement/Get-PiHoleDomain.ps1 | 28 +--- .../DomainManagement/New-PiHoleDomain.ps1 | 111 +++++++------- .../DomainManagement/Remove-PiHoleDomain.ps1 | 24 +-- .../DomainManagement/Update-PiHoleDomain.ps1 | 129 ++++++++-------- .../FTLInformation/Get-PiHoleInfoClient.ps1 | 2 +- .../FTLInformation/Get-PiHoleInfoDatabase.ps1 | 20 +-- .../FTLInformation/Get-PiHoleInfoFtl.ps1 | 20 +-- .../FTLInformation/Get-PiHoleInfoHost.ps1 | 20 +-- .../FTLInformation/Get-PiHoleInfoLogin.ps1 | 2 +- .../FTLInformation/Get-PiHoleInfoMessage.ps1 | 20 +-- .../Get-PiHoleInfoMessageCount.ps1 | 20 +-- .../FTLInformation/Get-PiHoleInfoMetrics.ps1 | 20 +-- .../FTLInformation/Get-PiHoleInfoSensors.ps1 | 20 +-- .../FTLInformation/Get-PiHoleInfoSystem.ps1 | 20 +-- .../FTLInformation/Get-PiHoleInfoVersion.ps1 | 20 +-- .../FTLInformation/Get-PiHoleLogDnsmasq.ps1 | 24 +-- .../FTLInformation/Get-PiHoleLogFtl.ps1 | 24 +-- .../FTLInformation/Get-PiHoleLogWebserver.ps1 | 24 +-- .../Remove-PiHoleInfoMessage.ps1 | 20 +-- .../GroupManagement/Get-PiHoleGroup.ps1 | 20 +-- .../GroupManagement/New-PiHoleGroup.ps1 | 79 +++++----- .../GroupManagement/Remove-PiHoleGroup.ps1 | 24 +-- .../GroupManagement/Update-PiHoleGroup.ps1 | 87 +++++------ .../Public/History/Get-PiHoleHistory.ps1 | 20 +-- .../History/Get-PiHoleHistoryClient.ps1 | 20 +-- .../History/Get-PiHoleHistoryDatabase.ps1 | 20 +-- .../Get-PiHoleHistoryDatabaseClient.ps1 | 20 +-- .../Public/ListManagement/Add-PiHoleList.ps1 | 140 +++++++++-------- .../Public/ListManagement/Get-PiHoleList.ps1 | 20 +-- .../ListManagement/Remove-PiHoleList.ps1 | 24 +-- .../Search-PiHoleListDomain.ps1 | 23 +-- .../ListManagement/Update-PiHoleList.ps1 | 141 +++++++++--------- .../Public/Metrics/Get-PiHoleQuery.ps1 | 24 +-- .../Get-PiHoleStatsDatabaseQueryType.ps1 | 20 +-- .../Get-PiHoleStatsDatabaseSummary.ps1 | 20 +-- .../Get-PiHoleStatsDatabaseTopClient.ps1 | 20 +-- .../Get-PiHoleStatsDatabaseTopDomain.ps1 | 20 +-- .../Get-PiHoleStatsDatabaseUpstream.ps1 | 20 +-- .../Get-PiHoleStatsQuerySuggestions.ps1 | 20 +-- .../Metrics/Get-PiHoleStatsQueryType.ps1 | 20 +-- .../Metrics/Get-PiHoleStatsRecentBlocked.ps1 | 19 +-- .../Public/Metrics/Get-PiHoleStatsSummary.ps1 | 20 +-- .../Metrics/Get-PiHoleStatsTopClient.ps1 | 20 +-- .../Metrics/Get-PiHoleStatsTopDomain.ps1 | 20 +-- .../Metrics/Get-PiHoleStatsUpstream.ps1 | 20 +-- .../Get-PiHoleNetworkDevice.ps1 | 24 +-- .../Get-PiHoleNetworkGateway.ps1 | 24 +-- .../Get-PiHoleNetworkInterface.ps1 | 24 +-- .../Get-PiHoleNetworkRoute.ps1 | 24 +-- .../Remove-PiHoleNetworkDevice.ps1 | 20 +-- PiHoleShell/Public/Padd/Get-PiHolePadd.ps1 | 20 +-- .../Get-PiHoleTeleporterDownload.ps1 | 22 +-- .../Teleporter/Import-PiHoleTeleporter.ps1 | 23 +-- 81 files changed, 798 insertions(+), 1762 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index c771c35..f2fb1e8 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -29,11 +29,12 @@ Found a security problem? Don't open a public issue. Follow the [security policy } ``` -6. **Write comment-based help** with `.SYNOPSIS`, `.DESCRIPTION`, every `.PARAMETER`, at least one `.EXAMPLE`, and a `HelpUri` pointing at the endpoint in Pi-hole's API docs. -7. **Export the function** in both places: +6. **Support `-WhatIf` and `-Confirm` on anything that changes the server.** Add `SupportsShouldProcess = $true` to `[CmdletBinding()]` and wrap the work in `if ($PSCmdlet.ShouldProcess(, )) { ... }`, with the API call inside it, so `-WhatIf` doesn't even log in. A wrapper around another state-changing function passes `-Confirm:$false` to it, so the user is asked only once (see `Add-PiHoleDnsRecord`). +7. **Write comment-based help** with `.SYNOPSIS`, `.DESCRIPTION`, every `.PARAMETER`, at least one `.EXAMPLE`, and a `HelpUri` pointing at the endpoint in Pi-hole's API docs. +8. **Export the function** in both places: - the `Export-ModuleMember` list in `PiHoleShell/PiHoleShell.psm1` - `FunctionsToExport` in `PiHoleShell/PiHoleShell.psd1`. This file is saved as UTF-16; keep that encoding when you edit it. -8. **Update the docs:** +9. **Update the docs:** - Run `tools/Update-ReadmeCommandReference.ps1` to regenerate the README's command reference. A CI check fails if it's out of date. - Add an entry to `tools/Update-ExampleOutput.ps1`, then run it to regenerate `docs/EXAMPLES.md`. This step needs a test server. @@ -63,7 +64,7 @@ New functions should come with an integration test covering normal output, `-Raw - **PSScriptAnalyzer** must report no issues. Run it locally with `Invoke-ScriptAnalyzer -Path .\PiHoleShell -Recurse`. - **SonarCloud** must pass its quality gate. In practice that usually means not duplicating code. -- **README sync** must pass (see step 8 above). +- **README sync** must pass (see step 9 above). - **Pester** integration tests run against the maintainer's own Pi-hole and can take up to an hour. If your PR comes from a fork, the maintainer may run them for you. ## Code of conduct diff --git a/PiHoleShell/Private/Invoke-PiHoleApiRequest.ps1 b/PiHoleShell/Private/Invoke-PiHoleApiRequest.ps1 index 48e6b17..87f6ecd 100644 --- a/PiHoleShell/Private/Invoke-PiHoleApiRequest.ps1 +++ b/PiHoleShell/Private/Invoke-PiHoleApiRequest.ps1 @@ -4,6 +4,11 @@ function Invoke-PiHoleApiRequest { # Logs in, calls one API endpoint and always logs out again - the request/session boilerplate # every public function otherwise repeats. Errors are left to propagate, so callers keep their # own catch block (and its ConvertTo-PiHoleFriendlyErrorMessage call) unchanged. + # + # Body is passed through as-is: callers serialize JSON bodies themselves (array bodies need + # ConvertTo-Json -InputObject or a leading comma to survive), and a hashtable Body on a Get + # becomes the query string. Form (multipart upload) and OutFile (binary download) are passed + # through the same way, and a Form request gets no ContentType so the multipart one is used. [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -13,18 +18,36 @@ function Invoke-PiHoleApiRequest { [Parameter(Mandatory = $true)] [string]$Endpoint, [string]$Method = "Get", + $Body, + [hashtable]$Form, + [string]$OutFile, [bool]$IgnoreSsl = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + # -ErrorAction Stop so a failed login (wrong password, server unreachable) ends here with + # its one error, instead of also sending the request without a session and reporting a + # second, less useful 401. + $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -ErrorAction Stop $Params = @{ Headers = @{sid = $($Sid) } Uri = "$($PiHoleServer.OriginalString)/api/$($Endpoint.TrimStart('/'))" Method = $Method SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + } + + if ($PSBoundParameters.ContainsKey('Form')) { + $Params.Form = $Form + } + else { + $Params.ContentType = "application/json" + } + if ($PSBoundParameters.ContainsKey('Body')) { + $Params.Body = $Body + } + if ($OutFile) { + $Params.OutFile = $OutFile } Invoke-RestMethod @Params -ErrorAction Stop diff --git a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 index ec03eb8..c7e7fd0 100644 --- a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 +++ b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 @@ -22,8 +22,7 @@ This will dump the response instead of the formatted object .EXAMPLE Invoke-PiHoleFlushLogs -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/action/flush/logs')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Flushes PiHole logs')] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/action/flush/logs')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Logs matches the Pi-hole API's own endpoint name, /action/flush/logs")] param ( @@ -36,36 +35,22 @@ Invoke-PiHoleFlushLogs -PiHoleServer "http://pihole.domain.com:8080" -Password " ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush DNS logs")) { + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/flush/logs' -Method Post - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/action/flush/logs" - Method = "Post" - ContentType = "application/json" - SkipCertificateCheck = $IgnoreSsl - } - - $Response = Invoke-RestMethod @Params - - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Status = "Flushed" + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = [PSCustomObject]@{ + Status = "Flushed" + } + Write-Output $Object } - Write-Output $Object } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 index d361243..9b8f97f 100644 --- a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 +++ b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 @@ -21,8 +21,7 @@ This will dump the response instead of the formatted object .EXAMPLE Invoke-PiHoleFlushNetwork -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/action/flush/network')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Flushes PiHole logs')] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/action/flush/network')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -34,36 +33,22 @@ Invoke-PiHoleFlushNetwork -PiHoleServer "http://pihole.domain.com:8080" -Passwor ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush network table")) { + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/flush/network' -Method Post - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/action/flush/network" - Method = "Post" - ContentType = "application/json" - SkipCertificateCheck = $IgnoreSsl - } - - $Response = Invoke-RestMethod @Params - - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Status = "Flushed" + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = [PSCustomObject]@{ + Status = "Flushed" + } + Write-Output $Object } - Write-Output $Object } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 b/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 index 60d8c7d..9c17fab 100644 --- a/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 +++ b/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 @@ -21,8 +21,7 @@ This will dump the response instead of the formatted object .EXAMPLE Invoke-PiHoleRestartDns -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/action/restartdns')] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Restarts PiHole DNS')] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/action/restartdns')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -34,36 +33,22 @@ Invoke-PiHoleRestartDns -PiHoleServer "http://pihole.domain.com:8080" -Password ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Restart DNS service")) { + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/restartdns' -Method Post - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/action/restartdns" - Method = "Post" - ContentType = "application/json" - SkipCertificateCheck = $IgnoreSsl - } - - $Response = Invoke-RestMethod @Params - - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Status = "Restarted" + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = [PSCustomObject]@{ + Status = "Restarted" + } + Write-Output $Object } - Write-Output $Object } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/Actions/Update-PiHoleActionsGravity.ps1 b/PiHoleShell/Public/Actions/Update-PiHoleActionsGravity.ps1 index 8791b6e..ef719ad 100644 --- a/PiHoleShell/Public/Actions/Update-PiHoleActionsGravity.ps1 +++ b/PiHoleShell/Public/Actions/Update-PiHoleActionsGravity.ps1 @@ -35,18 +35,16 @@ Update-PiHoleActionsGravity -PiHoleServer "http://pihole.domain.com:8080" -Passw [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/action/gravity" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'action/gravity' + Method = "Post" + IgnoreSsl = $IgnoreSsl } if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Update gravity")) { - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params if ($RawOutput) { Write-Output $Response @@ -65,10 +63,4 @@ Update-PiHoleActionsGravity -PiHoleServer "http://pihole.domain.com:8080" -Passw # returns while another run is in progress, instead of a bare "409 (Conflict)" Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } - } } \ No newline at end of file diff --git a/PiHoleShell/Public/Authentication/Get-PiHoleAuthStatus.ps1 b/PiHoleShell/Public/Authentication/Get-PiHoleAuthStatus.ps1 index 3666bb7..dc6c92e 100644 --- a/PiHoleShell/Public/Authentication/Get-PiHoleAuthStatus.ps1 +++ b/PiHoleShell/Public/Authentication/Get-PiHoleAuthStatus.ps1 @@ -71,7 +71,7 @@ Get-PiHoleAuthStatus -PiHoleServer "http://pihole.domain.com:8080" -Password "yo } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } finally { diff --git a/PiHoleShell/Public/Authentication/Get-PiHoleAuthTotp.ps1 b/PiHoleShell/Public/Authentication/Get-PiHoleAuthTotp.ps1 index 427248c..21b45b7 100644 --- a/PiHoleShell/Public/Authentication/Get-PiHoleAuthTotp.ps1 +++ b/PiHoleShell/Public/Authentication/Get-PiHoleAuthTotp.ps1 @@ -33,17 +33,7 @@ Get-PiHoleAuthTotp -PiHoleServer "http://pihole.domain.com:8080" -Password "your [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/auth/totp" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'auth/totp' if ($RawOutput) { Write-Output $Response @@ -65,12 +55,6 @@ Get-PiHoleAuthTotp -PiHoleServer "http://pihole.domain.com:8080" -Password "your } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Authentication/Get-PiHoleCurrentAuthSession.ps1 b/PiHoleShell/Public/Authentication/Get-PiHoleCurrentAuthSession.ps1 index c5aabcc..2f31db2 100644 --- a/PiHoleShell/Public/Authentication/Get-PiHoleCurrentAuthSession.ps1 +++ b/PiHoleShell/Public/Authentication/Get-PiHoleCurrentAuthSession.ps1 @@ -34,17 +34,7 @@ Get-PiHoleCurrentAuthSession -PiHoleServer "http://pihole.domain.com:8080" -Pass ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/auth/sessions" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'auth/sessions' if ($RawOutput) { Write-Output $Response @@ -72,12 +62,6 @@ Get-PiHoleCurrentAuthSession -PiHoleServer "http://pihole.domain.com:8080" -Pass } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Authentication/Remove-PiHoleAuthSession.ps1 b/PiHoleShell/Public/Authentication/Remove-PiHoleAuthSession.ps1 index d45042f..99023e9 100644 --- a/PiHoleShell/Public/Authentication/Remove-PiHoleAuthSession.ps1 +++ b/PiHoleShell/Public/Authentication/Remove-PiHoleAuthSession.ps1 @@ -22,9 +22,8 @@ The ID of the session to delete, as shown by Get-PiHoleCurrentAuthSession .EXAMPLE Remove-PiHoleAuthSession -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Id 3 #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Does not change state')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#delete-/auth/session/-id-')] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#delete-/auth/session/-id-')] param ( [Parameter(Mandatory = $true)] [System.URI]$PiHoleServer, @@ -35,33 +34,20 @@ Remove-PiHoleAuthSession -PiHoleServer "http://pihole.domain.com:8080" -Password ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/auth/session/$Id" - Method = "Delete" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + if ($PSCmdlet.ShouldProcess("Pi-Hole session $Id", "Remove session")) { + Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "auth/session/$Id" -Method Delete + + $ObjectFinal = @() + $Object = [PSCustomObject]@{ + Id = $Id + Status = "Removed" + } + $ObjectFinal = $Object + Write-Output $ObjectFinal } - - Invoke-RestMethod @Params - - $ObjectFinal = @() - $Object = [PSCustomObject]@{ - Id = $Id - Status = "Removed" - } - $ObjectFinal = $Object - Write-Output $ObjectFinal } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/Authentication/Request-PiHoleAuth.ps1 b/PiHoleShell/Public/Authentication/Request-PiHoleAuth.ps1 index 6428a97..a71adb7 100644 --- a/PiHoleShell/Public/Authentication/Request-PiHoleAuth.ps1 +++ b/PiHoleShell/Public/Authentication/Request-PiHoleAuth.ps1 @@ -24,6 +24,6 @@ function Request-PiHoleAuth { } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/ClientManagement/Get-PiHoleClient.ps1 b/PiHoleShell/Public/ClientManagement/Get-PiHoleClient.ps1 index 799ff99..8cb751b 100644 --- a/PiHoleShell/Public/ClientManagement/Get-PiHoleClient.ps1 +++ b/PiHoleShell/Public/ClientManagement/Get-PiHoleClient.ps1 @@ -41,24 +41,14 @@ Get-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Groups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Uri = "$($PiHoleServer.OriginalString)/api/clients" + $Endpoint = 'clients' if ($Client) { - $Uri += "/$([System.Uri]::EscapeDataString($Client))" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "/$([System.Uri]::EscapeDataString($Client))" } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -86,12 +76,6 @@ Get-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/ClientManagement/Get-PiHoleClientSuggestion.ps1 b/PiHoleShell/Public/ClientManagement/Get-PiHoleClientSuggestion.ps1 index e1ca8fc..ac3d5d6 100644 --- a/PiHoleShell/Public/ClientManagement/Get-PiHoleClientSuggestion.ps1 +++ b/PiHoleShell/Public/ClientManagement/Get-PiHoleClientSuggestion.ps1 @@ -33,17 +33,7 @@ Get-PiHoleClientSuggestion -PiHoleServer "http://pihole.domain.com:8080" -Passwo [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/clients/_suggestions" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'clients/_suggestions' if ($RawOutput) { Write-Output $Response @@ -64,12 +54,6 @@ Get-PiHoleClientSuggestion -PiHoleServer "http://pihole.domain.com:8080" -Passwo } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 b/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 index 703d473..ac9dc21 100644 --- a/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 +++ b/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 @@ -34,8 +34,7 @@ This will dump the response instead of the formatted object .EXAMPLE New-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Client "192.168.1.50" -Comment "Kid's tablet" #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/clients')] - [Diagnostics.CodeAnalysis.SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Ignoring for now")] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/clients')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -50,72 +49,66 @@ New-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a [bool]$RawOutput = $false ) try { - $FindMatchingClient = Get-PiHoleClient -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Client $Client + if ($PSCmdlet.ShouldProcess("Pi-Hole client $Client", "Create client")) { + $FindMatchingClient = Get-PiHoleClient -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Client $Client - if ($FindMatchingClient) { - throw "Client $Client already exists on $PiHoleServer! Please use Update-PiHoleClient to update it" - } - - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $Group) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id + if ($FindMatchingClient) { + throw "Client $Client already exists on $PiHoleServer! Please use Update-PiHoleClient to update it" } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $Group) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id + } + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + } + } - $Body = @{ - client = $Client - comment = $Comment - groups = [Object[]]($AllGroupsIds) - } + $Body = @{ + client = $Client + comment = $Comment + groups = [Object[]]($AllGroupsIds) + } - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/clients" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - ContentType = "application/json" - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'clients' + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params - if ($RawOutput) { - Write-Output $Response - } + if ($RawOutput) { + Write-Output $Response + } - else { - $ObjectFinal = foreach ($Item in $Response.clients) { - [PSCustomObject]@{ - Client = $Item.client - Name = $Item.name - Comment = $Item.comment - Groups = $AllGroupsNames - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + else { + $ObjectFinal = foreach ($Item in $Response.clients) { + [PSCustomObject]@{ + Client = $Item.client + Name = $Item.name + Comment = $Item.comment + Groups = $AllGroupsNames + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } } + Write-Output $ObjectFinal } - Write-Output $ObjectFinal } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/ClientManagement/Remove-PiHoleClient.ps1 b/PiHoleShell/Public/ClientManagement/Remove-PiHoleClient.ps1 index 0855c67..2eb6e27 100644 --- a/PiHoleShell/Public/ClientManagement/Remove-PiHoleClient.ps1 +++ b/PiHoleShell/Public/ClientManagement/Remove-PiHoleClient.ps1 @@ -41,8 +41,6 @@ Remove-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "you try { $Target = "Pi-Hole client $Client" if ($PSCmdlet.ShouldProcess($Target, "Remove client")) { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Body = @( @{ item = $Client @@ -52,15 +50,15 @@ Remove-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "you #For some reason this needs to be here to make it an array $Body = , $Body $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/clients:batchDelete" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 -Compress - ContentType = "application/json" + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'clients:batchDelete' + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 -Compress } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params if ($RawOutput) { Write-Output $Response @@ -79,12 +77,6 @@ Remove-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "you } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 b/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 index f7319af..0dbf91a 100644 --- a/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 +++ b/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 @@ -34,8 +34,7 @@ This will dump the response instead of the formatted object .EXAMPLE Update-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Client "192.168.1.50" -Comment "Kid's tablet" #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/clients/-client-')] - [Diagnostics.CodeAnalysis.SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Ignoring for now")] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/clients/-client-')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -51,79 +50,73 @@ Update-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "you ) try { - if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group')) { - throw "To update $Client, you must specify the Comment and/or Group parameter" - } + if ($PSCmdlet.ShouldProcess("Pi-Hole client $Client", "Update client")) { + if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group')) { + throw "To update $Client, you must specify the Comment and/or Group parameter" + } - $ExistingClient = Get-PiHoleClient -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Client $Client + $ExistingClient = Get-PiHoleClient -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Client $Client - if (-not $ExistingClient) { - throw "Cannot find $Client on $PiHoleServer! Please use New-PiHoleClient to create it" - } + if (-not $ExistingClient) { + throw "Cannot find $Client on $PiHoleServer! Please use New-PiHoleClient to create it" + } - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingClient.Groups } + $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingClient.Groups } - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $GroupNamesToResolve) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $GroupNamesToResolve) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id + } + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + } } - } - - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - # The API replaces the whole client entry on update, so any property not explicitly - # passed here is resent using the client's current value to avoid silently clearing it. - $Body = @{ - comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingClient.Comment } - groups = [Object[]]($AllGroupsIds) - } + # The API replaces the whole client entry on update, so any property not explicitly + # passed here is resent using the client's current value to avoid silently clearing it. + $Body = @{ + comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingClient.Comment } + groups = [Object[]]($AllGroupsIds) + } - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/clients/$([System.Uri]::EscapeDataString($Client))" - Method = "Put" - SkipCertificateCheck = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - ContentType = "application/json" - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "clients/$([System.Uri]::EscapeDataString($Client))" + Method = "Put" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params - if ($RawOutput) { - Write-Output $Response - } - else { - $ObjectFinal = foreach ($Item in $Response.clients) { - [PSCustomObject]@{ - Client = $Item.client - Name = $Item.name - Comment = $Item.comment - Groups = $AllGroupsNames - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + if ($RawOutput) { + Write-Output $Response + } + else { + $ObjectFinal = foreach ($Item in $Response.clients) { + [PSCustomObject]@{ + Client = $Item.client + Name = $Item.name + Comment = $Item.comment + Groups = $AllGroupsNames + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } } + Write-Output $ObjectFinal } - Write-Output $ObjectFinal } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Config/Add-PiHoleConfigArrayItem.ps1 b/PiHoleShell/Public/Config/Add-PiHoleConfigArrayItem.ps1 index 2d31bc9..d32f418 100644 --- a/PiHoleShell/Public/Config/Add-PiHoleConfigArrayItem.ps1 +++ b/PiHoleShell/Public/Config/Add-PiHoleConfigArrayItem.ps1 @@ -40,8 +40,7 @@ This will dump the response instead of the formatted object .EXAMPLE Add-PiHoleConfigArrayItem -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Element "dns/cnameRecords" -Value "alias.lan,target.lan" #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/config/-element-/-value-')] - [Diagnostics.CodeAnalysis.SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Ignoring for now")] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/config/-element-/-value-')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -57,45 +56,31 @@ Add-PiHoleConfigArrayItem -PiHoleServer "http://pihole.domain.com:8080" -Passwor [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Uri = "$($PiHoleServer.OriginalString)/api/config/$($Element.Trim('/'))/$([System.Uri]::EscapeDataString($Value))" - if ($PSBoundParameters.ContainsKey('Restart')) { - $Uri += "?restart=$($Restart.ToString().ToLower())" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Put" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } + if ($PSCmdlet.ShouldProcess("Pi-Hole config $Element", "Add item '$Value'")) { + $Endpoint = "config/$($Element.Trim('/'))/$([System.Uri]::EscapeDataString($Value))" + if ($PSBoundParameters.ContainsKey('Restart')) { + $Endpoint += "?restart=$($Restart.ToString().ToLower())" + } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint -Method Put - if ($RawOutput) { - Write-Output $Response - } - else { - # A successful add returns 201 Created with no body, so there's no response to - # build a rich object from. - $Object = [PSCustomObject]@{ - Element = $Element - Value = $Value - Status = "Added" + if ($RawOutput) { + Write-Output $Response + } + else { + # A successful add returns 201 Created with no body, so there's no response to + # build a rich object from. + $Object = [PSCustomObject]@{ + Element = $Element + Value = $Value + Status = "Added" + } + Write-Output $Object } - Write-Output $Object } } catch { Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } - } } diff --git a/PiHoleShell/Public/Config/Get-PiHoleConfig.ps1 b/PiHoleShell/Public/Config/Get-PiHoleConfig.ps1 index f6fe735..fa25259 100644 --- a/PiHoleShell/Public/Config/Get-PiHoleConfig.ps1 +++ b/PiHoleShell/Public/Config/Get-PiHoleConfig.ps1 @@ -52,25 +52,15 @@ Get-PiHoleConfig -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Uri = "$($PiHoleServer.OriginalString)/api/config" + $Endpoint = 'config' if ($Element) { - $Uri += "/$($Element.Trim('/'))" + $Endpoint += "/$($Element.Trim('/'))" } if ($PSBoundParameters.ContainsKey('Detailed')) { - $Uri += "?detailed=$($Detailed.ToString().ToLower())" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "?detailed=$($Detailed.ToString().ToLower())" } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -82,12 +72,6 @@ Get-PiHoleConfig -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Config/Get-PiHoleConfigProperty.ps1 b/PiHoleShell/Public/Config/Get-PiHoleConfigProperty.ps1 index f9f6d50..7566246 100644 --- a/PiHoleShell/Public/Config/Get-PiHoleConfigProperty.ps1 +++ b/PiHoleShell/Public/Config/Get-PiHoleConfigProperty.ps1 @@ -34,17 +34,7 @@ Get-PiHoleConfigProperty -PiHoleServer "http://pihole.domain.com:8080" -Password [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/config/_properties" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'config/_properties' if ($RawOutput) { Write-Output $Response @@ -62,12 +52,6 @@ Get-PiHoleConfigProperty -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Config/Remove-PiHoleConfigArrayItem.ps1 b/PiHoleShell/Public/Config/Remove-PiHoleConfigArrayItem.ps1 index f197ea8..18a3f43 100644 --- a/PiHoleShell/Public/Config/Remove-PiHoleConfigArrayItem.ps1 +++ b/PiHoleShell/Public/Config/Remove-PiHoleConfigArrayItem.ps1 @@ -57,22 +57,12 @@ Remove-PiHoleConfigArrayItem -PiHoleServer "http://pihole.domain.com:8080" -Pass try { $Target = "Pi-Hole config item $Value in $Element" if ($PSCmdlet.ShouldProcess($Target, "Remove config array item")) { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Uri = "$($PiHoleServer.OriginalString)/api/config/$($Element.Trim('/'))/$([System.Uri]::EscapeDataString($Value))" + $Endpoint = "config/$($Element.Trim('/'))/$([System.Uri]::EscapeDataString($Value))" if ($PSBoundParameters.ContainsKey('Restart')) { - $Uri += "?restart=$($Restart.ToString().ToLower())" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Delete" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "?restart=$($Restart.ToString().ToLower())" } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint -Method Delete if ($RawOutput) { Write-Output $Response @@ -94,10 +84,4 @@ Remove-PiHoleConfigArrayItem -PiHoleServer "http://pihole.domain.com:8080" -Pass catch { Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } - } } diff --git a/PiHoleShell/Public/Config/Set-PiHoleConfig.ps1 b/PiHoleShell/Public/Config/Set-PiHoleConfig.ps1 index 2c4eaf0..c1ff45f 100644 --- a/PiHoleShell/Public/Config/Set-PiHoleConfig.ps1 +++ b/PiHoleShell/Public/Config/Set-PiHoleConfig.ps1 @@ -39,8 +39,7 @@ This will dump the response instead of the formatted object .EXAMPLE Set-PiHoleConfig -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Settings @{ dns = @{ CNAMEdeepInspect = $true } } #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#patch-/config')] - [Diagnostics.CodeAnalysis.SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Ignoring for now")] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#patch-/config')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -54,44 +53,38 @@ Set-PiHoleConfig -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Uri = "$($PiHoleServer.OriginalString)/api/config" - if ($PSBoundParameters.ContainsKey('Restart')) { - $Uri += "?restart=$($Restart.ToString().ToLower())" - } - - $Body = @{ - config = $Settings - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Patch" - SkipCertificateCheck = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params - - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = ConvertTo-PiHolePascalCaseObject -InputObject $Response.config - Write-Output $Object + if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Change configuration")) { + $Endpoint = 'config' + if ($PSBoundParameters.ContainsKey('Restart')) { + $Endpoint += "?restart=$($Restart.ToString().ToLower())" + } + + $Body = @{ + config = $Settings + } + + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = $Endpoint + Method = "Patch" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } + + $Response = Invoke-PiHoleApiRequest @Params + + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = ConvertTo-PiHolePascalCaseObject -InputObject $Response.config + Write-Output $Object + } } } catch { Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } - } } diff --git a/PiHoleShell/Public/DHCP/Get-PiHoleDhcpLease.ps1 b/PiHoleShell/Public/DHCP/Get-PiHoleDhcpLease.ps1 index ee60678..fb70740 100644 --- a/PiHoleShell/Public/DHCP/Get-PiHoleDhcpLease.ps1 +++ b/PiHoleShell/Public/DHCP/Get-PiHoleDhcpLease.ps1 @@ -32,17 +32,7 @@ Get-PiHoleDhcpLease -PiHoleServer "http://pihole.domain.com:8080" -Password "you [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/dhcp/leases" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'dhcp/leases' if ($RawOutput) { Write-Output $Response @@ -70,12 +60,6 @@ Get-PiHoleDhcpLease -PiHoleServer "http://pihole.domain.com:8080" -Password "you } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/DHCP/Remove-PiHoleDhcpLease.ps1 b/PiHoleShell/Public/DHCP/Remove-PiHoleDhcpLease.ps1 index 19f43e0..93e3cb7 100644 --- a/PiHoleShell/Public/DHCP/Remove-PiHoleDhcpLease.ps1 +++ b/PiHoleShell/Public/DHCP/Remove-PiHoleDhcpLease.ps1 @@ -40,17 +40,7 @@ Remove-PiHoleDhcpLease -PiHoleServer "http://pihole.domain.com:8080" -Password " try { $Target = "Pi-Hole DHCP lease $Ip" if ($PSCmdlet.ShouldProcess($Target, "Remove DHCP lease")) { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/dhcp/leases/$Ip" - Method = "Delete" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "dhcp/leases/$Ip" -Method Delete if ($RawOutput) { Write-Output $Response @@ -69,12 +59,6 @@ Remove-PiHoleDhcpLease -PiHoleServer "http://pihole.domain.com:8080" -Password " } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/DnsControl/Add-PiHoleDnsRecord.ps1 b/PiHoleShell/Public/DnsControl/Add-PiHoleDnsRecord.ps1 index d69dba1..fbdc201 100644 --- a/PiHoleShell/Public/DnsControl/Add-PiHoleDnsRecord.ps1 +++ b/PiHoleShell/Public/DnsControl/Add-PiHoleDnsRecord.ps1 @@ -53,8 +53,7 @@ Add-PiHoleDnsRecord -PiHoleServer "http://pihole.domain.com:8080" -Password "you .EXAMPLE Add-PiHoleDnsRecord -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Type CNAME -Hostname "alias.local" -Target "test.local" -Ttl 300 #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/config/-element-/-value-')] - [Diagnostics.CodeAnalysis.SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Thin wrapper - Add-PiHoleConfigArrayItem (called internally) already carries this same suppression")] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/config/-element-/-value-')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -110,38 +109,41 @@ Add-PiHoleDnsRecord -PiHoleServer "http://pihole.domain.com:8080" -Password "you } } - $InnerParams = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Element = $Element - Value = $Value - IgnoreSsl = $IgnoreSsl - RawOutput = $RawOutput - } - if ($PSBoundParameters.ContainsKey('Restart')) { - $InnerParams.Restart = $Restart - } + if ($PSCmdlet.ShouldProcess("Pi-Hole DNS record '$Value' ($Type)", "Add DNS record")) { + $InnerParams = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Element = $Element + Value = $Value + IgnoreSsl = $IgnoreSsl + RawOutput = $RawOutput + Confirm = $false + } + if ($PSBoundParameters.ContainsKey('Restart')) { + $InnerParams.Restart = $Restart + } - $Response = Add-PiHoleConfigArrayItem @InnerParams -ErrorAction Stop + $Response = Add-PiHoleConfigArrayItem @InnerParams -ErrorAction Stop - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Type = $Type - Hostname = $Hostname - IPv4Address = $IPv4Address - IPv6Address = $IPv6Address - Target = $Target - Ttl = $Ttl - Status = $Response.Status + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = [PSCustomObject]@{ + Type = $Type + Hostname = $Hostname + IPv4Address = $IPv4Address + IPv6Address = $IPv6Address + Target = $Target + Ttl = $Ttl + Status = $Response.Status + } + Write-Output $Object } - Write-Output $Object } } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/DnsControl/Get-PiHoleDnsBlockingStatus.ps1 b/PiHoleShell/Public/DnsControl/Get-PiHoleDnsBlockingStatus.ps1 index f6fd6a6..d1871b0 100644 --- a/PiHoleShell/Public/DnsControl/Get-PiHoleDnsBlockingStatus.ps1 +++ b/PiHoleShell/Public/DnsControl/Get-PiHoleDnsBlockingStatus.ps1 @@ -33,17 +33,7 @@ Get-PiHoleDnsBlockingStatus -PiHoleServer "http://pihole.domain.com:8080" -Passw [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/dns/blocking" - Method = "Get" - ContentType = "application/json" - SkipCertificateCheck = $IgnoreSsl - } - - $Data = Invoke-RestMethod @Params + $Data = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'dns/blocking' if ($RawOutput) { Write-Output $Data @@ -61,13 +51,7 @@ Get-PiHoleDnsBlockingStatus -PiHoleServer "http://pihole.domain.com:8080" -Passw } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) break } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } - } } \ No newline at end of file diff --git a/PiHoleShell/Public/DnsControl/Get-PiHoleDnsRecord.ps1 b/PiHoleShell/Public/DnsControl/Get-PiHoleDnsRecord.ps1 index 0b98a36..b670f07 100644 --- a/PiHoleShell/Public/DnsControl/Get-PiHoleDnsRecord.ps1 +++ b/PiHoleShell/Public/DnsControl/Get-PiHoleDnsRecord.ps1 @@ -108,6 +108,6 @@ Get-PiHoleDnsRecord -PiHoleServer "http://pihole.domain.com:8080" -Password "you } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/DnsControl/Remove-PiHoleDnsRecord.ps1 b/PiHoleShell/Public/DnsControl/Remove-PiHoleDnsRecord.ps1 index e031278..fa46ef1 100644 --- a/PiHoleShell/Public/DnsControl/Remove-PiHoleDnsRecord.ps1 +++ b/PiHoleShell/Public/DnsControl/Remove-PiHoleDnsRecord.ps1 @@ -149,7 +149,7 @@ Get-PiHoleDnsRecord -PiHoleServer "http://pihole.domain.com:8080" -Password "you } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } } diff --git a/PiHoleShell/Public/DnsControl/Set-PiHoleDnsBlocking.ps1 b/PiHoleShell/Public/DnsControl/Set-PiHoleDnsBlocking.ps1 index 42a246c..2b82fcf 100644 --- a/PiHoleShell/Public/DnsControl/Set-PiHoleDnsBlocking.ps1 +++ b/PiHoleShell/Public/DnsControl/Set-PiHoleDnsBlocking.ps1 @@ -30,8 +30,7 @@ This will dump the response instead of the formatted object .EXAMPLE Set-PiHoleDnsBlocking -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Blocking $false -TimeInSeconds 60 #> - [CmdletBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Does not change state')] + [CmdletBinding(SupportsShouldProcess = $true)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -47,48 +46,42 @@ Set-PiHoleDnsBlocking -PiHoleServer "http://pihole.domain.com:8080" -Password "y ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Body = @{ - blocking = $Blocking - timer = $TimeInSeconds - } + if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Set DNS blocking to $Blocking")) { + $Body = @{ + blocking = $Blocking + timer = $TimeInSeconds + } - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/dns/blocking" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - Body = $Body | ConvertTo-Json -Depth 10 - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'dns/blocking' + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params - if ($RawOutput) { - Write-Output $Response - } + if ($RawOutput) { + Write-Output $Response + } - else { - if ($Response) { - $ObjectFinal = @() - $Object = [PSCustomObject]@{ - Blocking = $Response.blocking - TimeInSeconds = (Format-PiHoleSecond -TimeInSeconds $Response.timer).TimeInSeconds + else { + if ($Response) { + $ObjectFinal = @() + $Object = [PSCustomObject]@{ + Blocking = $Response.blocking + TimeInSeconds = (Format-PiHoleSecond -TimeInSeconds $Response.timer).TimeInSeconds + } + $ObjectFinal = $Object } - $ObjectFinal = $Object + Write-Output $ObjectFinal } - Write-Output $ObjectFinal } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/DomainManagement/Get-PiHoleDomain.ps1 b/PiHoleShell/Public/DomainManagement/Get-PiHoleDomain.ps1 index c099a2f..9f3e2b4 100644 --- a/PiHoleShell/Public/DomainManagement/Get-PiHoleDomain.ps1 +++ b/PiHoleShell/Public/DomainManagement/Get-PiHoleDomain.ps1 @@ -58,30 +58,20 @@ Get-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a throw "-Type and -Kind must both be specified when -Domain is specified" } - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Groups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Uri = "$($PiHoleServer.OriginalString)/api/domains" + $Endpoint = 'domains' if ($Type) { - $Uri += "/$($Type.ToLower())" + $Endpoint += "/$($Type.ToLower())" } if ($Kind) { - $Uri += "/$($Kind.ToLower())" + $Endpoint += "/$($Kind.ToLower())" } if ($Domain) { - $Uri += "/$([System.Uri]::EscapeDataString($Domain))" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "/$([System.Uri]::EscapeDataString($Domain))" } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -112,12 +102,6 @@ Get-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 b/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 index 6086a51..404e2c4 100644 --- a/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 +++ b/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 @@ -41,8 +41,7 @@ This will dump the response instead of the formatted object .EXAMPLE New-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Domain "example.com" -Type Allow -Kind Exact #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/domains/-type-/-kind-')] - [Diagnostics.CodeAnalysis.SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Ignoring for now")] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/domains/-type-/-kind-')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -64,76 +63,70 @@ New-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a [bool]$RawOutput = $false ) try { - $FindMatchingDomain = Get-PiHoleDomain -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Type $Type -Kind $Kind -Domain $Domain + if ($PSCmdlet.ShouldProcess("Pi-Hole domain $Domain ($Type/$Kind)", "Create domain")) { + $FindMatchingDomain = Get-PiHoleDomain -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Type $Type -Kind $Kind -Domain $Domain - if ($FindMatchingDomain) { - throw "Domain $Domain ($Type/$Kind) already exists on $PiHoleServer! Please use Update-PiHoleDomain to update it" - } - - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $Group) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id + if ($FindMatchingDomain) { + throw "Domain $Domain ($Type/$Kind) already exists on $PiHoleServer! Please use Update-PiHoleDomain to update it" } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $Group) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id + } + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + } + } - $Body = @{ - domain = $Domain - comment = $Comment - groups = [Object[]]($AllGroupsIds) - enabled = $Enabled - } + $Body = @{ + domain = $Domain + comment = $Comment + groups = [Object[]]($AllGroupsIds) + enabled = $Enabled + } - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/domains/$($Type.ToLower())/$($Kind.ToLower())" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - ContentType = "application/json" - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "domains/$($Type.ToLower())/$($Kind.ToLower())" + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params - if ($RawOutput) { - Write-Output $Response - } + if ($RawOutput) { + Write-Output $Response + } - else { - $ObjectFinal = foreach ($Item in $Response.domains) { - [PSCustomObject]@{ - Domain = $Item.domain - Unicode = $Item.unicode - Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() - Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() - Comment = $Item.comment - Groups = $AllGroupsNames - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + else { + $ObjectFinal = foreach ($Item in $Response.domains) { + [PSCustomObject]@{ + Domain = $Item.domain + Unicode = $Item.unicode + Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() + Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() + Comment = $Item.comment + Groups = $AllGroupsNames + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } } + Write-Output $ObjectFinal } - Write-Output $ObjectFinal } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/DomainManagement/Remove-PiHoleDomain.ps1 b/PiHoleShell/Public/DomainManagement/Remove-PiHoleDomain.ps1 index ce6a5c7..3e56dea 100644 --- a/PiHoleShell/Public/DomainManagement/Remove-PiHoleDomain.ps1 +++ b/PiHoleShell/Public/DomainManagement/Remove-PiHoleDomain.ps1 @@ -52,8 +52,6 @@ Remove-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "you try { $Target = "Pi-Hole domain $Domain of type $Type/$Kind" if ($PSCmdlet.ShouldProcess($Target, "Remove domain")) { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Body = @( @{ item = $Domain @@ -65,15 +63,15 @@ Remove-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "you #For some reason this needs to be here to make it an array $Body = , $Body $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/domains:batchDelete" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 -Compress - ContentType = "application/json" + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'domains:batchDelete' + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 -Compress } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params if ($RawOutput) { Write-Output $Response @@ -94,12 +92,6 @@ Remove-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "you } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 b/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 index 3e05ded..61b98c5 100644 --- a/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 +++ b/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 @@ -48,8 +48,7 @@ This will dump the response instead of the formatted object .EXAMPLE Update-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Domain "example.com" -Type Allow -Kind Exact -Enabled $false #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/domains/-type-/-kind-/-domain-')] - [Diagnostics.CodeAnalysis.SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Ignoring for now")] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/domains/-type-/-kind-/-domain-')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -72,87 +71,81 @@ Update-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "you ) try { - if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group') -and -not $PSBoundParameters.ContainsKey('Enabled')) { - throw "To update $Domain, you must specify the Comment, Group, and/or Enabled parameter" - } + if ($PSCmdlet.ShouldProcess("Pi-Hole domain $Domain ($Type/$Kind)", "Update domain")) { + if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group') -and -not $PSBoundParameters.ContainsKey('Enabled')) { + throw "To update $Domain, you must specify the Comment, Group, and/or Enabled parameter" + } - $ExistingDomain = Get-PiHoleDomain -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Type $Type -Kind $Kind -Domain $Domain + $ExistingDomain = Get-PiHoleDomain -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Type $Type -Kind $Kind -Domain $Domain - if (-not $ExistingDomain) { - throw "Cannot find $Domain of type $Type/$Kind on $PiHoleServer! Please use New-PiHoleDomain to create it" - } + if (-not $ExistingDomain) { + throw "Cannot find $Domain of type $Type/$Kind on $PiHoleServer! Please use New-PiHoleDomain to create it" + } - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingDomain.Groups } + $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingDomain.Groups } - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $GroupNamesToResolve) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $GroupNamesToResolve) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id + } + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + } } - } - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - # The API replaces the whole domain entry on update, so any property not explicitly - # passed here is resent using the domain's current value to avoid silently clearing it. - # Type/Kind are always resent as-is - see the .DESCRIPTION note on why this never moves - # a domain to a different Type/Kind. - $Body = @{ - type = $Type.ToLower() - kind = $Kind.ToLower() - comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingDomain.Comment } - groups = [Object[]]($AllGroupsIds) - enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $ExistingDomain.Enabled } - } + # The API replaces the whole domain entry on update, so any property not explicitly + # passed here is resent using the domain's current value to avoid silently clearing it. + # Type/Kind are always resent as-is - see the .DESCRIPTION note on why this never moves + # a domain to a different Type/Kind. + $Body = @{ + type = $Type.ToLower() + kind = $Kind.ToLower() + comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingDomain.Comment } + groups = [Object[]]($AllGroupsIds) + enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $ExistingDomain.Enabled } + } - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/domains/$($Type.ToLower())/$($Kind.ToLower())/$([System.Uri]::EscapeDataString($Domain))" - Method = "Put" - SkipCertificateCheck = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - ContentType = "application/json" - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "domains/$($Type.ToLower())/$($Kind.ToLower())/$([System.Uri]::EscapeDataString($Domain))" + Method = "Put" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params - if ($RawOutput) { - Write-Output $Response - } - else { - $ObjectFinal = foreach ($Item in $Response.domains) { - [PSCustomObject]@{ - Domain = $Item.domain - Unicode = $Item.unicode - Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() - Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() - Comment = $Item.comment - Groups = $AllGroupsNames - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + if ($RawOutput) { + Write-Output $Response + } + else { + $ObjectFinal = foreach ($Item in $Response.domains) { + [PSCustomObject]@{ + Domain = $Item.domain + Unicode = $Item.unicode + Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() + Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() + Comment = $Item.comment + Groups = $AllGroupsNames + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } } + Write-Output $ObjectFinal } - Write-Output $ObjectFinal } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoClient.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoClient.ps1 index 16b955d..9f91ded 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoClient.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoClient.ps1 @@ -60,6 +60,6 @@ Get-PiHoleInfoClient -PiHoleServer "http://pihole.domain.com:8080" } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoDatabase.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoDatabase.ps1 index a5b791a..a379950 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoDatabase.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoDatabase.ps1 @@ -35,17 +35,7 @@ Get-PiHoleInfoDatabase -PiHoleServer "http://pihole.domain.com:8080" -Password " ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/info/database" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'info/database' if ($RawOutput) { Write-Output $Response @@ -84,12 +74,6 @@ Get-PiHoleInfoDatabase -PiHoleServer "http://pihole.domain.com:8080" -Password " } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoFtl.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoFtl.ps1 index cfee248..bc4324b 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoFtl.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoFtl.ps1 @@ -35,17 +35,7 @@ Get-PiHoleInfoFtl -PiHoleServer "http://pihole.domain.com:8080" -Password "your- ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/info/ftl" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'info/ftl' if ($RawOutput) { Write-Output $Response @@ -97,12 +87,6 @@ Get-PiHoleInfoFtl -PiHoleServer "http://pihole.domain.com:8080" -Password "your- } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoHost.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoHost.ps1 index c573354..bec2f7f 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoHost.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoHost.ps1 @@ -33,17 +33,7 @@ Get-PiHoleInfoHost -PiHoleServer "http://pihole.domain.com:8080" -Password "your [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/info/host" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'info/host' if ($RawOutput) { Write-Output $Response @@ -71,12 +61,6 @@ Get-PiHoleInfoHost -PiHoleServer "http://pihole.domain.com:8080" -Password "your } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoLogin.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoLogin.ps1 index 914c889..81d9f7d 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoLogin.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoLogin.ps1 @@ -51,6 +51,6 @@ Get-PiHoleInfoLogin -PiHoleServer "http://pihole.domain.com:8080" } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMessage.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMessage.ps1 index c067a3e..ff84ffc 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMessage.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMessage.ps1 @@ -34,17 +34,7 @@ Get-PiHoleInfoMessage -PiHoleServer "http://pihole.domain.com:8080" -Password "y [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/info/messages" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'info/messages' if ($RawOutput) { Write-Output $Response @@ -76,12 +66,6 @@ Get-PiHoleInfoMessage -PiHoleServer "http://pihole.domain.com:8080" -Password "y } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMessageCount.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMessageCount.ps1 index b5f98f4..5d97159 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMessageCount.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMessageCount.ps1 @@ -34,17 +34,7 @@ Get-PiHoleInfoMessageCount -PiHoleServer "http://pihole.domain.com:8080" -Passwo ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/info/messages/count" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'info/messages/count' if ($RawOutput) { Write-Output $Response @@ -58,12 +48,6 @@ Get-PiHoleInfoMessageCount -PiHoleServer "http://pihole.domain.com:8080" -Passwo } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMetrics.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMetrics.ps1 index 22263a5..2901303 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMetrics.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoMetrics.ps1 @@ -35,17 +35,7 @@ Get-PiHoleInfoMetrics -PiHoleServer "http://pihole.domain.com:8080" -Password "y ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/info/metrics" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'info/metrics' if ($RawOutput) { Write-Output $Response @@ -106,12 +96,6 @@ Get-PiHoleInfoMetrics -PiHoleServer "http://pihole.domain.com:8080" -Password "y } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoSensors.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoSensors.ps1 index 8d056f7..75a0916 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoSensors.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoSensors.ps1 @@ -35,17 +35,7 @@ Get-PiHoleInfoSensors -PiHoleServer "http://pihole.domain.com:8080" -Password "y ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/info/sensors" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'info/sensors' if ($RawOutput) { Write-Output $Response @@ -80,12 +70,6 @@ Get-PiHoleInfoSensors -PiHoleServer "http://pihole.domain.com:8080" -Password "y } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoSystem.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoSystem.ps1 index cc148e1..87484fe 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoSystem.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoSystem.ps1 @@ -34,17 +34,7 @@ Get-PiHoleInfoSystem -PiHoleServer "http://pihole.domain.com:8080" -Password "yo ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/info/system" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'info/system' if ($RawOutput) { Write-Output $Response @@ -86,12 +76,6 @@ Get-PiHoleInfoSystem -PiHoleServer "http://pihole.domain.com:8080" -Password "yo } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoVersion.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoVersion.ps1 index f6a6b3b..5ebf034 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoVersion.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleInfoVersion.ps1 @@ -34,17 +34,7 @@ Get-PiHoleInfoVersion -PiHoleServer "http://pihole.domain.com:8080" -Password "y ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/info/version" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'info/version' if ($RawOutput) { Write-Output $Response @@ -95,12 +85,6 @@ Get-PiHoleInfoVersion -PiHoleServer "http://pihole.domain.com:8080" -Password "y } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogDnsmasq.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogDnsmasq.ps1 index 274fec4..059f6be 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogDnsmasq.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogDnsmasq.ps1 @@ -39,22 +39,12 @@ Get-PiHoleLogDnsmasq -PiHoleServer "http://pihole.domain.com:8080" -Password "yo [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Uri = "$($PiHoleServer.OriginalString)/api/logs/dnsmasq" + $Endpoint = 'logs/dnsmasq' if ($PSBoundParameters.ContainsKey('NextID')) { - $Uri += "?nextID=$NextID" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "?nextID=$NextID" } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -80,12 +70,6 @@ Get-PiHoleLogDnsmasq -PiHoleServer "http://pihole.domain.com:8080" -Password "yo } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogFtl.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogFtl.ps1 index 9f5dbcb..2096fae 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogFtl.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogFtl.ps1 @@ -39,22 +39,12 @@ Get-PiHoleLogFtl -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Uri = "$($PiHoleServer.OriginalString)/api/logs/ftl" + $Endpoint = 'logs/ftl' if ($PSBoundParameters.ContainsKey('NextID')) { - $Uri += "?nextID=$NextID" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "?nextID=$NextID" } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -80,12 +70,6 @@ Get-PiHoleLogFtl -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogWebserver.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogWebserver.ps1 index feaff04..b9946a6 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogWebserver.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogWebserver.ps1 @@ -39,22 +39,12 @@ Get-PiHoleLogWebserver -PiHoleServer "http://pihole.domain.com:8080" -Password " [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Uri = "$($PiHoleServer.OriginalString)/api/logs/webserver" + $Endpoint = 'logs/webserver' if ($PSBoundParameters.ContainsKey('NextID')) { - $Uri += "?nextID=$NextID" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "?nextID=$NextID" } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -80,12 +70,6 @@ Get-PiHoleLogWebserver -PiHoleServer "http://pihole.domain.com:8080" -Password " } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/FTLInformation/Remove-PiHoleInfoMessage.ps1 b/PiHoleShell/Public/FTLInformation/Remove-PiHoleInfoMessage.ps1 index 53b498f..e812f57 100644 --- a/PiHoleShell/Public/FTLInformation/Remove-PiHoleInfoMessage.ps1 +++ b/PiHoleShell/Public/FTLInformation/Remove-PiHoleInfoMessage.ps1 @@ -45,17 +45,7 @@ Remove-PiHoleInfoMessage -PiHoleServer "http://pihole.domain.com:8080" -Password $MessageIdPath = $MessageId -join ',' if ($PSCmdlet.ShouldProcess("Pi-Hole diagnosis message(s) $MessageIdPath on $PiHoleServer", "Delete")) { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/info/messages/$MessageIdPath" - Method = "Delete" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "info/messages/$MessageIdPath" -Method Delete if ($RawOutput) { Write-Output $Response @@ -72,12 +62,6 @@ Remove-PiHoleInfoMessage -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/GroupManagement/Get-PiHoleGroup.ps1 b/PiHoleShell/Public/GroupManagement/Get-PiHoleGroup.ps1 index 6f9e260..8f6b47c 100644 --- a/PiHoleShell/Public/GroupManagement/Get-PiHoleGroup.ps1 +++ b/PiHoleShell/Public/GroupManagement/Get-PiHoleGroup.ps1 @@ -40,17 +40,7 @@ Get-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your-ap [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/groups" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'groups' if ($RawOutput) { Write-Output $Response @@ -96,12 +86,6 @@ Get-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your-ap } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 b/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 index 696019f..649f162 100644 --- a/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 +++ b/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 @@ -31,8 +31,7 @@ This will dump the response instead of the formatted object .EXAMPLE New-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -GroupName "Kids" #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/groups')] - [Diagnostics.CodeAnalysis.SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Ignoring for now")] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/groups')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -48,59 +47,53 @@ New-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your-ap ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + if ($PSCmdlet.ShouldProcess("Pi-Hole group $GroupName", "Create group")) { + $GetGroupName = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -GroupName $GroupName - $GetGroupName = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -GroupName $GroupName - - if ($GetGroupName) { - Write-Warning -Message "Group $GroupName already exists" - } - - else { - $Body = @{ - comment = $Comment - enabled = $Enabled - name = $GroupName + if ($GetGroupName) { + Write-Warning -Message "Group $GroupName already exists" } - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/groups" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - Body = $Body | ConvertTo-Json -Depth 10 - } + else { + $Body = @{ + comment = $Comment + enabled = $Enabled + name = $GroupName + } + + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'groups' + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params - if ($RawOutput) { - Write-Output $Response - } + if ($RawOutput) { + Write-Output $Response + } - else { - $ObjectFinal = foreach ($Item in $Response.groups) { - [PSCustomObject]@{ - Name = $Item.name - Comment = $Item.comment - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + else { + $ObjectFinal = foreach ($Item in $Response.groups) { + [PSCustomObject]@{ + Name = $Item.name + Comment = $Item.comment + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } } + Write-Output $ObjectFinal } - Write-Output $ObjectFinal } } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/GroupManagement/Remove-PiHoleGroup.ps1 b/PiHoleShell/Public/GroupManagement/Remove-PiHoleGroup.ps1 index fdac7a1..36d7324 100644 --- a/PiHoleShell/Public/GroupManagement/Remove-PiHoleGroup.ps1 +++ b/PiHoleShell/Public/GroupManagement/Remove-PiHoleGroup.ps1 @@ -53,8 +53,6 @@ Remove-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your } } - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - # @() forces this to stay an array even for a single name - without it, PowerShell # unwraps a one-item foreach result to a bare hashtable, which ConvertTo-Json then # serializes as a JSON object instead of an array, and the API rejects it with 400. @@ -63,17 +61,17 @@ Remove-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your }) $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/groups:batchDelete" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'groups:batchDelete' + Method = "Post" + IgnoreSsl = $IgnoreSsl # -InputObject (not piped) so ConvertTo-Json serializes the array as-is instead of # unwrapping it into individual pipeline objects first. - Body = ConvertTo-Json -InputObject $Body -Depth 10 -Compress - ContentType = "application/json" + Body = ConvertTo-Json -InputObject $Body -Depth 10 -Compress } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params if ($RawOutput) { Write-Output $Response @@ -94,12 +92,6 @@ Remove-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 b/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 index 41e5c11..a353905 100644 --- a/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 +++ b/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 @@ -34,8 +34,7 @@ This will dump the response instead of the formatted object Update-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -GroupName "Kids" -Enabled $false #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] - [Diagnostics.CodeAnalysis.SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Ignoring for now")] - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/groups/-name-')] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/groups/-name-')] param ( [Parameter(Mandatory = $true)] [System.URI]$PiHoleServer, @@ -50,62 +49,56 @@ Update-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + if ($PSCmdlet.ShouldProcess("Pi-Hole group $GroupName", "Update group")) { + $GetGroupName = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -GroupName $GroupName - $GetGroupName = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -GroupName $GroupName - - if (-not $GetGroupName) { - throw "Cannot find $GroupName on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } + if (-not $GetGroupName) { + throw "Cannot find $GroupName on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + } - if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Enabled')) { - throw "To update $GroupName, you must specify the Comment and/or Enabled parameter" - } + if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Enabled')) { + throw "To update $GroupName, you must specify the Comment and/or Enabled parameter" + } - # The API replaces the whole group on update, so any property not explicitly passed - # here is resent using the group's current value to avoid silently clearing it. - $Body = @{ - name = $GroupName - comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $GetGroupName.Comment } - enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $GetGroupName.Enabled } - } + # The API replaces the whole group on update, so any property not explicitly passed + # here is resent using the group's current value to avoid silently clearing it. + $Body = @{ + name = $GroupName + comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $GetGroupName.Comment } + enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $GetGroupName.Enabled } + } - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/groups/$GroupName" - Method = "Put" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - Body = $Body | ConvertTo-Json -Depth 10 - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "groups/$GroupName" + Method = "Put" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params - if ($RawOutput) { - Write-Output $Response - } - else { - $ObjectFinal = foreach ($Item in $Response.groups) { - [PSCustomObject]@{ - Name = $Item.name - Comment = $Item.comment - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + if ($RawOutput) { + Write-Output $Response + } + else { + $ObjectFinal = foreach ($Item in $Response.groups) { + [PSCustomObject]@{ + Name = $Item.name + Comment = $Item.comment + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } } + Write-Output $ObjectFinal } - Write-Output $ObjectFinal } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/History/Get-PiHoleHistory.ps1 b/PiHoleShell/Public/History/Get-PiHoleHistory.ps1 index 45d618c..43448b4 100644 --- a/PiHoleShell/Public/History/Get-PiHoleHistory.ps1 +++ b/PiHoleShell/Public/History/Get-PiHoleHistory.ps1 @@ -36,17 +36,7 @@ Get-PiHoleHistory -PiHoleServer "http://pihole.domain.com:8080" -Password "your- ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/history" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'history' if ($RawOutput) { Write-Output $Response @@ -66,12 +56,6 @@ Get-PiHoleHistory -PiHoleServer "http://pihole.domain.com:8080" -Password "your- } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/History/Get-PiHoleHistoryClient.ps1 b/PiHoleShell/Public/History/Get-PiHoleHistoryClient.ps1 index 9487f41..841ada9 100644 --- a/PiHoleShell/Public/History/Get-PiHoleHistoryClient.ps1 +++ b/PiHoleShell/Public/History/Get-PiHoleHistoryClient.ps1 @@ -43,17 +43,7 @@ Get-PiHoleHistoryClient -PiHoleServer "http://pihole.domain.com:8080" -Password ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/history/clients?N=$MaxResult" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "history/clients?N=$MaxResult" if ($RawOutput) { Write-Output $Response @@ -82,12 +72,6 @@ Get-PiHoleHistoryClient -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/History/Get-PiHoleHistoryDatabase.ps1 b/PiHoleShell/Public/History/Get-PiHoleHistoryDatabase.ps1 index 4a63e83..42fdd34 100644 --- a/PiHoleShell/Public/History/Get-PiHoleHistoryDatabase.ps1 +++ b/PiHoleShell/Public/History/Get-PiHoleHistoryDatabase.ps1 @@ -47,20 +47,10 @@ Get-PiHoleHistoryDatabase -PiHoleServer "http://pihole.domain.com:8080" -Passwor ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $FromUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $From).UnixTime $UntilUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $Until).UnixTime - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/history/database?from=$FromUnixTime&until=$UntilUnixTime" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "history/database?from=$FromUnixTime&until=$UntilUnixTime" if ($RawOutput) { Write-Output $Response @@ -80,12 +70,6 @@ Get-PiHoleHistoryDatabase -PiHoleServer "http://pihole.domain.com:8080" -Passwor } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/History/Get-PiHoleHistoryDatabaseClient.ps1 b/PiHoleShell/Public/History/Get-PiHoleHistoryDatabaseClient.ps1 index 3272c43..45d96e6 100644 --- a/PiHoleShell/Public/History/Get-PiHoleHistoryDatabaseClient.ps1 +++ b/PiHoleShell/Public/History/Get-PiHoleHistoryDatabaseClient.ps1 @@ -52,20 +52,10 @@ Get-PiHoleHistoryDatabaseClient -PiHoleServer "http://pihole.domain.com:8080" -P ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $FromUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $From).UnixTime $UntilUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $Until).UnixTime - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/history/database/clients?from=$FromUnixTime&until=$UntilUnixTime" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "history/database/clients?from=$FromUnixTime&until=$UntilUnixTime" if ($RawOutput) { Write-Output $Response @@ -90,12 +80,6 @@ Get-PiHoleHistoryDatabaseClient -PiHoleServer "http://pihole.domain.com:8080" -P } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 b/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 index d1b4ad3..755e430 100644 --- a/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 +++ b/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 @@ -37,7 +37,7 @@ This will dump the response instead of the formatted object .EXAMPLE Add-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Address "https://hosts-file.net/ad_servers.txt" -Type Block #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/lists')] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/lists')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -56,93 +56,87 @@ Add-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app [bool]$RawOutput = $false ) try { - $FindMatchingList = Get-PiHoleList -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl | Where-Object { $_.Address -eq $Address } + if ($PSCmdlet.ShouldProcess("Pi-Hole list $Address", "Add list")) { + $FindMatchingList = Get-PiHoleList -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl | Where-Object { $_.Address -eq $Address } - if ($FindMatchingList) { - throw "List $Address already exists on $PiHoleServer! Please use Update-PiHoleList to update the list" - } + if ($FindMatchingList) { + throw "List $Address already exists on $PiHoleServer! Please use Update-PiHoleList to update the list" + } - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $Group) { + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $Group) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - Write-Verbose -Message "Found Group $($FoundGroup.Name) with $($FoundGroup.Id)" - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id + Write-Verbose -Message "Found Group $($FoundGroup.Name) with $($FoundGroup.Id)" + } + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + } } - } - - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Body = @{ - address = $Address - groups = [Object[]]($AllGroupsIds) - comment = $Comment - enabled = $Enabled - } + $Body = @{ + address = $Address + groups = [Object[]]($AllGroupsIds) + comment = $Comment + enabled = $Enabled + } - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/lists?type=$($Type.ToLower())" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - ContentType = "application/json" - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "lists?type=$($Type.ToLower())" + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params - if ($RawOutput) { - Write-Output $Response - } + if ($RawOutput) { + Write-Output $Response + } - else { - $ObjectFinal = @() - foreach ($Item in $Response.lists) { - if ($Item.date_updated -eq 0) { - $DateUpdated = $null - } - else { - $DateUpdated = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } + else { + $ObjectFinal = @() + foreach ($Item in $Response.lists) { + if ($Item.date_updated -eq 0) { + $DateUpdated = $null + } + else { + $DateUpdated = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } + + $Object = [PSCustomObject]@{ + Address = $Item.address + Comment = $Item.comment + Groups = $AllGroupsNames + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() + DateUpdated = $DateUpdated + Number = $Item.number + InvalidDomains = $Item.invalid_domains + AbpEntries = $Item.abp_entries + Status = $Item.status + } + if ($Object) { + $ObjectFinal += $Object + } - $Object = [PSCustomObject]@{ - Address = $Item.address - Comment = $Item.comment - Groups = $AllGroupsNames - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() - DateUpdated = $DateUpdated - Number = $Item.number - InvalidDomains = $Item.invalid_domains - AbpEntries = $Item.abp_entries - Status = $Item.status - } - if ($Object) { - $ObjectFinal += $Object } - + Write-Output $ObjectFinal } - Write-Output $ObjectFinal } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/ListManagement/Get-PiHoleList.ps1 b/PiHoleShell/Public/ListManagement/Get-PiHoleList.ps1 index 70d58f8..c892c4c 100644 --- a/PiHoleShell/Public/ListManagement/Get-PiHoleList.ps1 +++ b/PiHoleShell/Public/ListManagement/Get-PiHoleList.ps1 @@ -40,19 +40,9 @@ Get-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Groups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/lists/$List" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "lists/$List" if ($RawOutput) { Write-Output $Response @@ -98,12 +88,6 @@ Get-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/ListManagement/Remove-PiHoleList.ps1 b/PiHoleShell/Public/ListManagement/Remove-PiHoleList.ps1 index 0fdc319..a7c297c 100644 --- a/PiHoleShell/Public/ListManagement/Remove-PiHoleList.ps1 +++ b/PiHoleShell/Public/ListManagement/Remove-PiHoleList.ps1 @@ -46,8 +46,6 @@ Remove-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your- try { $Target = "Pi-Hole list $Address of type $Type" if ($PSCmdlet.ShouldProcess($Target, "Remove list")) { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Body = @( @{ item = $Address @@ -58,15 +56,15 @@ Remove-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your- #For some reason this needs to be here to make it an array $Body = , $Body $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/lists:batchDelete" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 -Compress - ContentType = "application/json" + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'lists:batchDelete' + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 -Compress } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params if ($RawOutput) { Write-Output $Response @@ -86,12 +84,6 @@ Remove-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your- } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/ListManagement/Search-PiHoleListDomain.ps1 b/PiHoleShell/Public/ListManagement/Search-PiHoleListDomain.ps1 index 8ddb971..a49b7ef 100644 --- a/PiHoleShell/Public/ListManagement/Search-PiHoleListDomain.ps1 +++ b/PiHoleShell/Public/ListManagement/Search-PiHoleListDomain.ps1 @@ -45,23 +45,20 @@ Search-PiHoleListDomain -PiHoleServer "http://pihole.domain.com:8080" -Password [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Body = @{ n = $MaxResults partial = $PartialMatch } $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/search/$Domain" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - Body = $Body - ContentType = "application/json" + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "search/$Domain" + IgnoreSsl = $IgnoreSsl + Body = $Body } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params if ($RawOutput) { Write-Output $Response @@ -112,13 +109,7 @@ Search-PiHoleListDomain -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) break } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } - } } \ No newline at end of file diff --git a/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 b/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 index d6789fe..cd1740d 100644 --- a/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 +++ b/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 @@ -39,8 +39,7 @@ This will dump the response instead of the formatted object .EXAMPLE Update-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password" -Address "https://hosts-file.net/ad_servers.txt" -Type Block -Enabled $false #> - [CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/lists/-list-')] - [Diagnostics.CodeAnalysis.SuppressMessage("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Ignoring for now")] + [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#put-/lists/-list-')] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] param ( [Parameter(Mandatory = $true)] @@ -60,93 +59,87 @@ Update-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your- ) try { - if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group') -and -not $PSBoundParameters.ContainsKey('Enabled')) { - throw "To update $Address, you must specify the Comment, Group, and/or Enabled parameter" - } - - $ExistingList = Get-PiHoleList -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -List $Address | Where-Object { $_.Type -eq $Type } - - if (-not $ExistingList) { - throw "Cannot find $Address of type $Type on $PiHoleServer! Please use Add-PiHoleList to create it" - } - - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingList.Groups } - - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $GroupNamesToResolve) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id + if ($PSCmdlet.ShouldProcess("Pi-Hole list $Address", "Update list")) { + if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group') -and -not $PSBoundParameters.ContainsKey('Enabled')) { + throw "To update $Address, you must specify the Comment, Group, and/or Enabled parameter" } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $ExistingList = Get-PiHoleList -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -List $Address | Where-Object { $_.Type -eq $Type } - # The API replaces the whole list on update, so any property not explicitly passed here - # is resent using the list's current value to avoid silently clearing it. - $Body = @{ - comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingList.Comment } - groups = [Object[]]($AllGroupsIds) - enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $ExistingList.Enabled } - } + if (-not $ExistingList) { + throw "Cannot find $Address of type $Type on $PiHoleServer! Please use Add-PiHoleList to create it" + } - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/lists/$Address`?type=$($Type.ToLower())" - Method = "Put" - SkipCertificateCheck = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - ContentType = "application/json" - } + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Response = Invoke-RestMethod @Params + $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingList.Groups } - if ($RawOutput) { - Write-Output $Response - } - else { - $ObjectFinal = foreach ($Item in $Response.lists) { - if ($Item.date_updated -eq 0) { - $DateUpdated = $null + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $GroupNamesToResolve) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id } else { - $DateUpdated = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" } + } + + # The API replaces the whole list on update, so any property not explicitly passed here + # is resent using the list's current value to avoid silently clearing it. + $Body = @{ + comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingList.Comment } + groups = [Object[]]($AllGroupsIds) + enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $ExistingList.Enabled } + } + + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "lists/$Address`?type=$($Type.ToLower())" + Method = "Put" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - [PSCustomObject]@{ - Address = $Item.address - Comment = $Item.comment - Groups = $AllGroupsNames - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() - DateUpdated = $DateUpdated - Number = $Item.number - InvalidDomains = $Item.invalid_domains - AbpEntries = $Item.abp_entries - Status = $Item.status + $Response = Invoke-PiHoleApiRequest @Params + + if ($RawOutput) { + Write-Output $Response + } + else { + $ObjectFinal = foreach ($Item in $Response.lists) { + if ($Item.date_updated -eq 0) { + $DateUpdated = $null + } + else { + $DateUpdated = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } + + [PSCustomObject]@{ + Address = $Item.address + Comment = $Item.comment + Groups = $AllGroupsNames + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() + DateUpdated = $DateUpdated + Number = $Item.number + InvalidDomains = $Item.invalid_domains + AbpEntries = $Item.abp_entries + Status = $Item.status + } } + Write-Output $ObjectFinal } - Write-Output $ObjectFinal } } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleQuery.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleQuery.ps1 index 7f6ab61..fe08bc6 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleQuery.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleQuery.ps1 @@ -97,8 +97,6 @@ Get-PiHoleQuery -PiHoleServer "http://pihole.domain.com:8080" -Password "your-ap [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $QueryParams = [System.Collections.ArrayList]@() if ($PSBoundParameters.ContainsKey('From')) { $QueryParams.Add("from=$From") | Out-Null } if ($PSBoundParameters.ContainsKey('Until')) { $QueryParams.Add("until=$Until") | Out-Null } @@ -115,20 +113,12 @@ Get-PiHoleQuery -PiHoleServer "http://pihole.domain.com:8080" -Password "your-ap if ($Dnssec) { $QueryParams.Add("dnssec=$([System.Uri]::EscapeDataString($Dnssec))") | Out-Null } if ($PSBoundParameters.ContainsKey('Disk')) { $QueryParams.Add("disk=$($Disk.ToString().ToLower())") | Out-Null } - $Uri = "$($PiHoleServer.OriginalString)/api/queries" + $Endpoint = 'queries' if ($QueryParams.Count -gt 0) { - $Uri += "?" + ($QueryParams -join '&') - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "?" + ($QueryParams -join '&') } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -164,12 +154,6 @@ Get-PiHoleQuery -PiHoleServer "http://pihole.domain.com:8080" -Password "your-ap } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseQueryType.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseQueryType.ps1 index 5350d52..2972a14 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseQueryType.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseQueryType.ps1 @@ -45,20 +45,10 @@ Get-PiHoleStatsDatabaseQueryType -PiHoleServer "http://pihole.domain.com:8080" - ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $FromUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $From).UnixTime $UntilUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $Until).UnixTime - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/database/query_types?from=$FromUnixTime&until=$UntilUnixTime" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "stats/database/query_types?from=$FromUnixTime&until=$UntilUnixTime" if ($RawOutput) { Write-Output $Response @@ -76,12 +66,6 @@ Get-PiHoleStatsDatabaseQueryType -PiHoleServer "http://pihole.domain.com:8080" - } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseSummary.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseSummary.ps1 index 54bc13c..b2e2a5e 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseSummary.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseSummary.ps1 @@ -45,20 +45,10 @@ Get-PiHoleStatsDatabaseSummary -PiHoleServer "http://pihole.domain.com:8080" -Pa ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $FromUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $From).UnixTime $UntilUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $Until).UnixTime - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/database/summary?from=$FromUnixTime&until=$UntilUnixTime" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "stats/database/summary?from=$FromUnixTime&until=$UntilUnixTime" if ($RawOutput) { Write-Output $Response @@ -75,12 +65,6 @@ Get-PiHoleStatsDatabaseSummary -PiHoleServer "http://pihole.domain.com:8080" -Pa } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseTopClient.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseTopClient.ps1 index 4125f56..60dc0e9 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseTopClient.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseTopClient.ps1 @@ -53,8 +53,6 @@ Get-PiHoleStatsDatabaseTopClient -PiHoleServer "http://pihole.domain.com:8080" - ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - switch ($Blocked) { $false { $BlockedParam = "false" } $true { $BlockedParam = "true" } @@ -66,15 +64,7 @@ Get-PiHoleStatsDatabaseTopClient -PiHoleServer "http://pihole.domain.com:8080" - $FromUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $From).UnixTime $UntilUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $Until).UnixTime - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/database/top_clients?from=$FromUnixTime&until=$UntilUnixTime&blocked=$BlockedParam&count=$MaxResult" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "stats/database/top_clients?from=$FromUnixTime&until=$UntilUnixTime&blocked=$BlockedParam&count=$MaxResult" if ($RawOutput) { Write-Output $Response @@ -95,12 +85,6 @@ Get-PiHoleStatsDatabaseTopClient -PiHoleServer "http://pihole.domain.com:8080" - } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseTopDomain.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseTopDomain.ps1 index 67c4dcd..9fd6a72 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseTopDomain.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseTopDomain.ps1 @@ -53,8 +53,6 @@ Get-PiHoleStatsDatabaseTopDomain -PiHoleServer "http://pihole.domain.com:8080" - ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - switch ($Blocked) { $false { $BlockedParam = "false" } $true { $BlockedParam = "true" } @@ -66,15 +64,7 @@ Get-PiHoleStatsDatabaseTopDomain -PiHoleServer "http://pihole.domain.com:8080" - $FromUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $From).UnixTime $UntilUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $Until).UnixTime - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/database/top_domains?from=$FromUnixTime&until=$UntilUnixTime&blocked=$BlockedParam&count=$MaxResult" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "stats/database/top_domains?from=$FromUnixTime&until=$UntilUnixTime&blocked=$BlockedParam&count=$MaxResult" if ($RawOutput) { Write-Output $Response @@ -94,12 +84,6 @@ Get-PiHoleStatsDatabaseTopDomain -PiHoleServer "http://pihole.domain.com:8080" - } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseUpstream.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseUpstream.ps1 index 0d35e26..300fe0e 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseUpstream.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsDatabaseUpstream.ps1 @@ -45,20 +45,10 @@ Get-PiHoleStatsDatabaseUpstream -PiHoleServer "http://pihole.domain.com:8080" -P ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $FromUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $From).UnixTime $UntilUnixTime = (Convert-LocalTimeToPiHoleUnixTime -Date $Until).UnixTime - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/database/upstreams?from=$FromUnixTime&until=$UntilUnixTime" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "stats/database/upstreams?from=$FromUnixTime&until=$UntilUnixTime" if ($RawOutput) { Write-Output $Response @@ -84,12 +74,6 @@ Get-PiHoleStatsDatabaseUpstream -PiHoleServer "http://pihole.domain.com:8080" -P } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsQuerySuggestions.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsQuerySuggestions.ps1 index 30421bf..74e0f41 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsQuerySuggestions.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsQuerySuggestions.ps1 @@ -35,17 +35,7 @@ Get-PiHoleStatsQuerySuggestions -PiHoleServer "http://pihole.domain.com:8080" -P ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/queries/suggestions" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'queries/suggestions' if ($RawOutput) { Write-Output $Response @@ -66,12 +56,6 @@ Get-PiHoleStatsQuerySuggestions -PiHoleServer "http://pihole.domain.com:8080" -P } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsQueryType.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsQueryType.ps1 index 9345b0b..e60c844 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsQueryType.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsQueryType.ps1 @@ -33,17 +33,7 @@ Get-PiHoleStatsQueryType -PiHoleServer "http://pihole.domain.com:8080" -Password ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/query_types" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'stats/query_types' if ($RawOutput) { Write-Output $Response @@ -61,12 +51,6 @@ Get-PiHoleStatsQueryType -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsRecentBlocked.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsRecentBlocked.ps1 index 9c36705..18e736f 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsRecentBlocked.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsRecentBlocked.ps1 @@ -36,17 +36,8 @@ Get-PiHoleStatsRecentBlocked -PiHoleServer "http://pihole.domain.com:8080" -Pass [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl Write-Verbose -Message "MaxResults - $MaxResult" - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/recent_blocked?count=$MaxResult" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "stats/recent_blocked?count=$MaxResult" if ($RawOutput) { Write-Output $Response @@ -66,14 +57,8 @@ Get-PiHoleStatsRecentBlocked -PiHoleServer "http://pihole.domain.com:8080" -Pass } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) break } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } - } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsSummary.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsSummary.ps1 index 8598870..0a2fa0a 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsSummary.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsSummary.ps1 @@ -32,17 +32,7 @@ Get-PiHoleStatsSummary -PiHoleServer "http://pihole.domain.com:8080" -Password " [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/summary" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'stats/summary' if ($RawOutput) { Write-Output $Response @@ -125,12 +115,6 @@ Get-PiHoleStatsSummary -PiHoleServer "http://pihole.domain.com:8080" -Password " } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsTopClient.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsTopClient.ps1 index eb4444a..66d44c5 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsTopClient.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsTopClient.ps1 @@ -40,8 +40,6 @@ Get-PiHoleStatsTopClient -PiHoleServer "http://pihole.domain.com:8080" -Password [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - switch ($Blocked) { $false { $BlockedParam = "false" } $true { $BlockedParam = "true" } @@ -50,15 +48,7 @@ Get-PiHoleStatsTopClient -PiHoleServer "http://pihole.domain.com:8080" -Password Write-Verbose "Blocked: $BlockedParam" Write-Verbose "MaxResult: $MaxResult" - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/top_clients?blocked=$BlockedParam&count=$MaxResult" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "stats/top_clients?blocked=$BlockedParam&count=$MaxResult" if ($RawOutput) { Write-Output $Response @@ -80,13 +70,7 @@ Get-PiHoleStatsTopClient -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) break } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } - } } \ No newline at end of file diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsTopDomain.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsTopDomain.ps1 index 460a0d8..83d120b 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsTopDomain.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsTopDomain.ps1 @@ -40,8 +40,6 @@ Get-PiHoleStatsTopDomain -PiHoleServer "http://pihole.domain.com:8080" -Password [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - switch ($Blocked) { $false { $BlockedParam = "false" } $true { $BlockedParam = "true" } @@ -50,15 +48,7 @@ Get-PiHoleStatsTopDomain -PiHoleServer "http://pihole.domain.com:8080" -Password Write-Verbose "Blocked: $BlockedParam" Write-Verbose "MaxResult: $MaxResult" - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/top_domains?blocked=$BlockedParam&count=$MaxResult" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "stats/top_domains?blocked=$BlockedParam&count=$MaxResult" if ($RawOutput) { Write-Output $Response @@ -78,12 +68,6 @@ Get-PiHoleStatsTopDomain -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Metrics/Get-PiHoleStatsUpstream.ps1 b/PiHoleShell/Public/Metrics/Get-PiHoleStatsUpstream.ps1 index 52ede7b..d022725 100644 --- a/PiHoleShell/Public/Metrics/Get-PiHoleStatsUpstream.ps1 +++ b/PiHoleShell/Public/Metrics/Get-PiHoleStatsUpstream.ps1 @@ -34,17 +34,7 @@ Get-PiHoleStatsUpstream -PiHoleServer "http://pihole.domain.com:8080" -Password ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/stats/upstreams" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'stats/upstreams' if ($RawOutput) { Write-Output $Response @@ -70,12 +60,6 @@ Get-PiHoleStatsUpstream -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkDevice.ps1 b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkDevice.ps1 index f47050b..5326e47 100644 --- a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkDevice.ps1 +++ b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkDevice.ps1 @@ -44,8 +44,6 @@ Get-PiHoleNetworkDevice -PiHoleServer "http://pihole.domain.com:8080" -Password [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $QueryParams = [System.Collections.ArrayList]@() if ($PSBoundParameters.ContainsKey('MaxDevices')) { $QueryParams.Add("max_devices=$MaxDevices") | Out-Null @@ -54,20 +52,12 @@ Get-PiHoleNetworkDevice -PiHoleServer "http://pihole.domain.com:8080" -Password $QueryParams.Add("max_addresses=$MaxAddresses") | Out-Null } - $Uri = "$($PiHoleServer.OriginalString)/api/network/devices" + $Endpoint = 'network/devices' if ($QueryParams.Count -gt 0) { - $Uri += "?" + ($QueryParams -join '&') - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "?" + ($QueryParams -join '&') } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -99,12 +89,6 @@ Get-PiHoleNetworkDevice -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkGateway.ps1 b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkGateway.ps1 index ee6c1d3..9c7ac31 100644 --- a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkGateway.ps1 +++ b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkGateway.ps1 @@ -39,22 +39,12 @@ Get-PiHoleNetworkGateway -PiHoleServer "http://pihole.domain.com:8080" -Password [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Uri = "$($PiHoleServer.OriginalString)/api/network/gateway" + $Endpoint = 'network/gateway' if ($PSBoundParameters.ContainsKey('Detailed')) { - $Uri += "?detailed=$($Detailed.ToString().ToLower())" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "?detailed=$($Detailed.ToString().ToLower())" } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -66,12 +56,6 @@ Get-PiHoleNetworkGateway -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkInterface.ps1 b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkInterface.ps1 index 8efbc42..04679f6 100644 --- a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkInterface.ps1 +++ b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkInterface.ps1 @@ -39,22 +39,12 @@ Get-PiHoleNetworkInterface -PiHoleServer "http://pihole.domain.com:8080" -Passwo [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Uri = "$($PiHoleServer.OriginalString)/api/network/interfaces" + $Endpoint = 'network/interfaces' if ($PSBoundParameters.ContainsKey('Detailed')) { - $Uri += "?detailed=$($Detailed.ToString().ToLower())" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "?detailed=$($Detailed.ToString().ToLower())" } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -66,12 +56,6 @@ Get-PiHoleNetworkInterface -PiHoleServer "http://pihole.domain.com:8080" -Passwo } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkRoute.ps1 b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkRoute.ps1 index e6f3740..4373d6f 100644 --- a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkRoute.ps1 +++ b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkRoute.ps1 @@ -39,22 +39,12 @@ Get-PiHoleNetworkRoute -PiHoleServer "http://pihole.domain.com:8080" -Password " [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Uri = "$($PiHoleServer.OriginalString)/api/network/routes" + $Endpoint = 'network/routes' if ($PSBoundParameters.ContainsKey('Detailed')) { - $Uri += "?detailed=$($Detailed.ToString().ToLower())" - } - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = $Uri - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" + $Endpoint += "?detailed=$($Detailed.ToString().ToLower())" } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint if ($RawOutput) { Write-Output $Response @@ -66,12 +56,6 @@ Get-PiHoleNetworkRoute -PiHoleServer "http://pihole.domain.com:8080" -Password " } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/NetworkInformation/Remove-PiHoleNetworkDevice.ps1 b/PiHoleShell/Public/NetworkInformation/Remove-PiHoleNetworkDevice.ps1 index aac1ee4..41582de 100644 --- a/PiHoleShell/Public/NetworkInformation/Remove-PiHoleNetworkDevice.ps1 +++ b/PiHoleShell/Public/NetworkInformation/Remove-PiHoleNetworkDevice.ps1 @@ -40,17 +40,7 @@ Remove-PiHoleNetworkDevice -PiHoleServer "http://pihole.domain.com:8080" -Passwo try { $Target = "Pi-Hole network device $DeviceId" if ($PSCmdlet.ShouldProcess($Target, "Remove device")) { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/network/devices/$DeviceId" - Method = "Delete" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "network/devices/$DeviceId" -Method Delete if ($RawOutput) { Write-Output $Response @@ -69,12 +59,6 @@ Remove-PiHoleNetworkDevice -PiHoleServer "http://pihole.domain.com:8080" -Passwo } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Padd/Get-PiHolePadd.ps1 b/PiHoleShell/Public/Padd/Get-PiHolePadd.ps1 index c2b1a82..5144e64 100644 --- a/PiHoleShell/Public/Padd/Get-PiHolePadd.ps1 +++ b/PiHoleShell/Public/Padd/Get-PiHolePadd.ps1 @@ -34,17 +34,7 @@ Get-PiHolePadd -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app [bool]$RawOutput = $false ) try { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/padd" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - ContentType = "application/json" - } - - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'padd' if ($RawOutput) { Write-Output $Response @@ -131,12 +121,6 @@ Get-PiHolePadd -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } \ No newline at end of file diff --git a/PiHoleShell/Public/Teleporter/Get-PiHoleTeleporterDownload.ps1 b/PiHoleShell/Public/Teleporter/Get-PiHoleTeleporterDownload.ps1 index 07fc347..762d68b 100644 --- a/PiHoleShell/Public/Teleporter/Get-PiHoleTeleporterDownload.ps1 +++ b/PiHoleShell/Public/Teleporter/Get-PiHoleTeleporterDownload.ps1 @@ -49,17 +49,15 @@ Get-PiHoleTeleporterDownload -PiHoleServer "http://pihole.domain.com:8080" -Pass throw "$OutFile already exists!" } - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/teleporter" - Method = "Get" - SkipCertificateCheck = $IgnoreSsl - OutFile = $OutFile + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'teleporter' + IgnoreSsl = $IgnoreSsl + OutFile = $OutFile } - Invoke-RestMethod @Params + Invoke-PiHoleApiRequest @Params $Object = [PSCustomObject]@{ FileName = $FileName @@ -71,12 +69,6 @@ Get-PiHoleTeleporterDownload -PiHoleServer "http://pihole.domain.com:8080" -Pass } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } diff --git a/PiHoleShell/Public/Teleporter/Import-PiHoleTeleporter.ps1 b/PiHoleShell/Public/Teleporter/Import-PiHoleTeleporter.ps1 index a9471d0..9ffb0b4 100644 --- a/PiHoleShell/Public/Teleporter/Import-PiHoleTeleporter.ps1 +++ b/PiHoleShell/Public/Teleporter/Import-PiHoleTeleporter.ps1 @@ -106,8 +106,6 @@ Import-PiHoleTeleporter -PiHoleServer "http://pihole.domain.com:8080" -Password $Target = "Pi-Hole at $PiHoleServer" $Action = "Import Teleporter archive '$FilePath' (this will overwrite your current configuration)" if ($PSCmdlet.ShouldProcess($Target, $Action)) { - $Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $FormData = @{ file = Get-Item -Path $FilePath } @@ -130,14 +128,15 @@ Import-PiHoleTeleporter -PiHoleServer "http://pihole.domain.com:8080" -Password } $Params = @{ - Headers = @{sid = $($Sid) } - Uri = "$($PiHoleServer.OriginalString)/api/teleporter" - Method = "Post" - SkipCertificateCheck = $IgnoreSsl - Form = $FormData + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'teleporter' + Method = "Post" + IgnoreSsl = $IgnoreSsl + Form = $FormData } - $Response = Invoke-RestMethod @Params + $Response = Invoke-PiHoleApiRequest @Params if ($RawOutput) { Write-Output $Response @@ -154,12 +153,6 @@ Import-PiHoleTeleporter -PiHoleServer "http://pihole.domain.com:8080" -Password } catch { - Write-Error -Message $_.Exception.Message - } - - finally { - if ($Sid) { - Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl - } + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) } } From 94ebb1dc652cacb80e18aa17775a9c6299715bc1 Mon Sep 17 00:00:00 2001 From: Mike Madeja Date: Sat, 7 Nov 2026 07:46:25 -0600 Subject: [PATCH 2/5] refactor: use a guard clause for ShouldProcess Wrapping each function body in if ($PSCmdlet.ShouldProcess(...)) added a nesting level, pushing New-PiHoleClient, New-PiHoleDomain and Update-PiHoleGroup over SonarCloud's cognitive complexity limit of 15. Return early instead, which also restores the bodies' original indentation so unchanged lines stop showing up as new code. Co-Authored-By: Claude Opus 5.5 --- .../Public/Actions/Invoke-PiHoleFlushLogs.ps1 | 22 +-- .../Actions/Invoke-PiHoleFlushNetwork.ps1 | 22 +-- .../Actions/Restart-PiHoleDnsService.ps1 | 22 +-- .../Remove-PiHoleAuthSession.ps1 | 22 +-- .../ClientManagement/New-PiHoleClient.ps1 | 94 +++++++------ .../ClientManagement/Update-PiHoleClient.ps1 | 104 +++++++------- .../Config/Add-PiHoleConfigArrayItem.ps1 | 38 ++--- .../Public/Config/Set-PiHoleConfig.ps1 | 50 +++---- .../Public/DnsControl/Add-PiHoleDnsRecord.ps1 | 58 ++++---- .../DnsControl/Set-PiHoleDnsBlocking.ps1 | 54 +++---- .../DomainManagement/New-PiHoleDomain.ps1 | 102 +++++++------- .../DomainManagement/Update-PiHoleDomain.ps1 | 120 ++++++++-------- .../GroupManagement/New-PiHoleGroup.ps1 | 70 +++++----- .../GroupManagement/Update-PiHoleGroup.ps1 | 78 ++++++----- .../Public/ListManagement/Add-PiHoleList.ps1 | 132 +++++++++--------- .../ListManagement/Update-PiHoleList.ps1 | 132 +++++++++--------- 16 files changed, 576 insertions(+), 544 deletions(-) diff --git a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 index c7e7fd0..1d49718 100644 --- a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 +++ b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 @@ -35,18 +35,20 @@ Invoke-PiHoleFlushLogs -PiHoleServer "http://pihole.domain.com:8080" -Password " ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush DNS logs")) { - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/flush/logs' -Method Post + if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush DNS logs")) { + return + } - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Status = "Flushed" - } - Write-Output $Object + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/flush/logs' -Method Post + + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = [PSCustomObject]@{ + Status = "Flushed" } + Write-Output $Object } } diff --git a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 index 9b8f97f..27a279b 100644 --- a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 +++ b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 @@ -33,18 +33,20 @@ Invoke-PiHoleFlushNetwork -PiHoleServer "http://pihole.domain.com:8080" -Passwor ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush network table")) { - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/flush/network' -Method Post + if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush network table")) { + return + } - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Status = "Flushed" - } - Write-Output $Object + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/flush/network' -Method Post + + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = [PSCustomObject]@{ + Status = "Flushed" } + Write-Output $Object } } diff --git a/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 b/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 index 9c17fab..2a34d3a 100644 --- a/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 +++ b/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 @@ -33,18 +33,20 @@ Invoke-PiHoleRestartDns -PiHoleServer "http://pihole.domain.com:8080" -Password ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Restart DNS service")) { - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/restartdns' -Method Post + if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Restart DNS service")) { + return + } - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Status = "Restarted" - } - Write-Output $Object + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/restartdns' -Method Post + + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = [PSCustomObject]@{ + Status = "Restarted" } + Write-Output $Object } } diff --git a/PiHoleShell/Public/Authentication/Remove-PiHoleAuthSession.ps1 b/PiHoleShell/Public/Authentication/Remove-PiHoleAuthSession.ps1 index 99023e9..9c52f12 100644 --- a/PiHoleShell/Public/Authentication/Remove-PiHoleAuthSession.ps1 +++ b/PiHoleShell/Public/Authentication/Remove-PiHoleAuthSession.ps1 @@ -34,17 +34,19 @@ Remove-PiHoleAuthSession -PiHoleServer "http://pihole.domain.com:8080" -Password ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole session $Id", "Remove session")) { - Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "auth/session/$Id" -Method Delete - - $ObjectFinal = @() - $Object = [PSCustomObject]@{ - Id = $Id - Status = "Removed" - } - $ObjectFinal = $Object - Write-Output $ObjectFinal + if (-not $PSCmdlet.ShouldProcess("Pi-Hole session $Id", "Remove session")) { + return } + + Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint "auth/session/$Id" -Method Delete + + $ObjectFinal = @() + $Object = [PSCustomObject]@{ + Id = $Id + Status = "Removed" + } + $ObjectFinal = $Object + Write-Output $ObjectFinal } catch { diff --git a/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 b/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 index ac9dc21..76d6e09 100644 --- a/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 +++ b/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 @@ -49,62 +49,64 @@ New-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a [bool]$RawOutput = $false ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole client $Client", "Create client")) { - $FindMatchingClient = Get-PiHoleClient -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Client $Client + if (-not $PSCmdlet.ShouldProcess("Pi-Hole client $Client", "Create client")) { + return + } - if ($FindMatchingClient) { - throw "Client $Client already exists on $PiHoleServer! Please use Update-PiHoleClient to update it" - } + $FindMatchingClient = Get-PiHoleClient -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Client $Client - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $Group) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + if ($FindMatchingClient) { + throw "Client $Client already exists on $PiHoleServer! Please use Update-PiHoleClient to update it" + } - $Body = @{ - client = $Client - comment = $Comment - groups = [Object[]]($AllGroupsIds) + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $Group) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id } - - $Params = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Endpoint = 'clients' - Method = "Post" - IgnoreSsl = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" } + } - $Response = Invoke-PiHoleApiRequest @Params + $Body = @{ + client = $Client + comment = $Comment + groups = [Object[]]($AllGroupsIds) + } - if ($RawOutput) { - Write-Output $Response - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'clients' + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - else { - $ObjectFinal = foreach ($Item in $Response.clients) { - [PSCustomObject]@{ - Client = $Item.client - Name = $Item.name - Comment = $Item.comment - Groups = $AllGroupsNames - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } + $Response = Invoke-PiHoleApiRequest @Params + + if ($RawOutput) { + Write-Output $Response + } + + else { + $ObjectFinal = foreach ($Item in $Response.clients) { + [PSCustomObject]@{ + Client = $Item.client + Name = $Item.name + Comment = $Item.comment + Groups = $AllGroupsNames + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime } - Write-Output $ObjectFinal } + Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 b/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 index 0dbf91a..04cea28 100644 --- a/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 +++ b/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 @@ -50,69 +50,71 @@ Update-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "you ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole client $Client", "Update client")) { - if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group')) { - throw "To update $Client, you must specify the Comment and/or Group parameter" - } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole client $Client", "Update client")) { + return + } - $ExistingClient = Get-PiHoleClient -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Client $Client + if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group')) { + throw "To update $Client, you must specify the Comment and/or Group parameter" + } - if (-not $ExistingClient) { - throw "Cannot find $Client on $PiHoleServer! Please use New-PiHoleClient to create it" - } + $ExistingClient = Get-PiHoleClient -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Client $Client - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + if (-not $ExistingClient) { + throw "Cannot find $Client on $PiHoleServer! Please use New-PiHoleClient to create it" + } - $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingClient.Groups } + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $GroupNamesToResolve) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingClient.Groups } - # The API replaces the whole client entry on update, so any property not explicitly - # passed here is resent using the client's current value to avoid silently clearing it. - $Body = @{ - comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingClient.Comment } - groups = [Object[]]($AllGroupsIds) + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $GroupNamesToResolve) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id } - - $Params = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Endpoint = "clients/$([System.Uri]::EscapeDataString($Client))" - Method = "Put" - IgnoreSsl = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" } + } - $Response = Invoke-PiHoleApiRequest @Params + # The API replaces the whole client entry on update, so any property not explicitly + # passed here is resent using the client's current value to avoid silently clearing it. + $Body = @{ + comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingClient.Comment } + groups = [Object[]]($AllGroupsIds) + } - if ($RawOutput) { - Write-Output $Response - } - else { - $ObjectFinal = foreach ($Item in $Response.clients) { - [PSCustomObject]@{ - Client = $Item.client - Name = $Item.name - Comment = $Item.comment - Groups = $AllGroupsNames - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "clients/$([System.Uri]::EscapeDataString($Client))" + Method = "Put" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } + + $Response = Invoke-PiHoleApiRequest @Params + + if ($RawOutput) { + Write-Output $Response + } + else { + $ObjectFinal = foreach ($Item in $Response.clients) { + [PSCustomObject]@{ + Client = $Item.client + Name = $Item.name + Comment = $Item.comment + Groups = $AllGroupsNames + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime } - Write-Output $ObjectFinal } + Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/Config/Add-PiHoleConfigArrayItem.ps1 b/PiHoleShell/Public/Config/Add-PiHoleConfigArrayItem.ps1 index d32f418..371c13b 100644 --- a/PiHoleShell/Public/Config/Add-PiHoleConfigArrayItem.ps1 +++ b/PiHoleShell/Public/Config/Add-PiHoleConfigArrayItem.ps1 @@ -56,27 +56,29 @@ Add-PiHoleConfigArrayItem -PiHoleServer "http://pihole.domain.com:8080" -Passwor [bool]$RawOutput = $false ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole config $Element", "Add item '$Value'")) { - $Endpoint = "config/$($Element.Trim('/'))/$([System.Uri]::EscapeDataString($Value))" - if ($PSBoundParameters.ContainsKey('Restart')) { - $Endpoint += "?restart=$($Restart.ToString().ToLower())" - } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole config $Element", "Add item '$Value'")) { + return + } + + $Endpoint = "config/$($Element.Trim('/'))/$([System.Uri]::EscapeDataString($Value))" + if ($PSBoundParameters.ContainsKey('Restart')) { + $Endpoint += "?restart=$($Restart.ToString().ToLower())" + } - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint -Method Put + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint -Method Put - if ($RawOutput) { - Write-Output $Response - } - else { - # A successful add returns 201 Created with no body, so there's no response to - # build a rich object from. - $Object = [PSCustomObject]@{ - Element = $Element - Value = $Value - Status = "Added" - } - Write-Output $Object + if ($RawOutput) { + Write-Output $Response + } + else { + # A successful add returns 201 Created with no body, so there's no response to + # build a rich object from. + $Object = [PSCustomObject]@{ + Element = $Element + Value = $Value + Status = "Added" } + Write-Output $Object } } diff --git a/PiHoleShell/Public/Config/Set-PiHoleConfig.ps1 b/PiHoleShell/Public/Config/Set-PiHoleConfig.ps1 index c1ff45f..dac22d7 100644 --- a/PiHoleShell/Public/Config/Set-PiHoleConfig.ps1 +++ b/PiHoleShell/Public/Config/Set-PiHoleConfig.ps1 @@ -53,34 +53,36 @@ Set-PiHoleConfig -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a [bool]$RawOutput = $false ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Change configuration")) { - $Endpoint = 'config' - if ($PSBoundParameters.ContainsKey('Restart')) { - $Endpoint += "?restart=$($Restart.ToString().ToLower())" - } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Change configuration")) { + return + } + + $Endpoint = 'config' + if ($PSBoundParameters.ContainsKey('Restart')) { + $Endpoint += "?restart=$($Restart.ToString().ToLower())" + } - $Body = @{ - config = $Settings - } + $Body = @{ + config = $Settings + } - $Params = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Endpoint = $Endpoint - Method = "Patch" - IgnoreSsl = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = $Endpoint + Method = "Patch" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - $Response = Invoke-PiHoleApiRequest @Params + $Response = Invoke-PiHoleApiRequest @Params - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = ConvertTo-PiHolePascalCaseObject -InputObject $Response.config - Write-Output $Object - } + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = ConvertTo-PiHolePascalCaseObject -InputObject $Response.config + Write-Output $Object } } diff --git a/PiHoleShell/Public/DnsControl/Add-PiHoleDnsRecord.ps1 b/PiHoleShell/Public/DnsControl/Add-PiHoleDnsRecord.ps1 index fbdc201..d03ee36 100644 --- a/PiHoleShell/Public/DnsControl/Add-PiHoleDnsRecord.ps1 +++ b/PiHoleShell/Public/DnsControl/Add-PiHoleDnsRecord.ps1 @@ -109,37 +109,39 @@ Add-PiHoleDnsRecord -PiHoleServer "http://pihole.domain.com:8080" -Password "you } } - if ($PSCmdlet.ShouldProcess("Pi-Hole DNS record '$Value' ($Type)", "Add DNS record")) { - $InnerParams = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Element = $Element - Value = $Value - IgnoreSsl = $IgnoreSsl - RawOutput = $RawOutput - Confirm = $false - } - if ($PSBoundParameters.ContainsKey('Restart')) { - $InnerParams.Restart = $Restart - } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole DNS record '$Value' ($Type)", "Add DNS record")) { + return + } - $Response = Add-PiHoleConfigArrayItem @InnerParams -ErrorAction Stop + $InnerParams = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Element = $Element + Value = $Value + IgnoreSsl = $IgnoreSsl + RawOutput = $RawOutput + Confirm = $false + } + if ($PSBoundParameters.ContainsKey('Restart')) { + $InnerParams.Restart = $Restart + } - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Type = $Type - Hostname = $Hostname - IPv4Address = $IPv4Address - IPv6Address = $IPv6Address - Target = $Target - Ttl = $Ttl - Status = $Response.Status - } - Write-Output $Object + $Response = Add-PiHoleConfigArrayItem @InnerParams -ErrorAction Stop + + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = [PSCustomObject]@{ + Type = $Type + Hostname = $Hostname + IPv4Address = $IPv4Address + IPv6Address = $IPv6Address + Target = $Target + Ttl = $Ttl + Status = $Response.Status } + Write-Output $Object } } diff --git a/PiHoleShell/Public/DnsControl/Set-PiHoleDnsBlocking.ps1 b/PiHoleShell/Public/DnsControl/Set-PiHoleDnsBlocking.ps1 index 2b82fcf..ecfa5bc 100644 --- a/PiHoleShell/Public/DnsControl/Set-PiHoleDnsBlocking.ps1 +++ b/PiHoleShell/Public/DnsControl/Set-PiHoleDnsBlocking.ps1 @@ -46,38 +46,40 @@ Set-PiHoleDnsBlocking -PiHoleServer "http://pihole.domain.com:8080" -Password "y ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Set DNS blocking to $Blocking")) { - $Body = @{ - blocking = $Blocking - timer = $TimeInSeconds - } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Set DNS blocking to $Blocking")) { + return + } - $Params = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Endpoint = 'dns/blocking' - Method = "Post" - IgnoreSsl = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - } + $Body = @{ + blocking = $Blocking + timer = $TimeInSeconds + } - $Response = Invoke-PiHoleApiRequest @Params + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'dns/blocking' + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - if ($RawOutput) { - Write-Output $Response - } + $Response = Invoke-PiHoleApiRequest @Params + + if ($RawOutput) { + Write-Output $Response + } - else { - if ($Response) { - $ObjectFinal = @() - $Object = [PSCustomObject]@{ - Blocking = $Response.blocking - TimeInSeconds = (Format-PiHoleSecond -TimeInSeconds $Response.timer).TimeInSeconds - } - $ObjectFinal = $Object + else { + if ($Response) { + $ObjectFinal = @() + $Object = [PSCustomObject]@{ + Blocking = $Response.blocking + TimeInSeconds = (Format-PiHoleSecond -TimeInSeconds $Response.timer).TimeInSeconds } - Write-Output $ObjectFinal + $ObjectFinal = $Object } + Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 b/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 index 404e2c4..c466675 100644 --- a/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 +++ b/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 @@ -63,66 +63,68 @@ New-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a [bool]$RawOutput = $false ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole domain $Domain ($Type/$Kind)", "Create domain")) { - $FindMatchingDomain = Get-PiHoleDomain -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Type $Type -Kind $Kind -Domain $Domain + if (-not $PSCmdlet.ShouldProcess("Pi-Hole domain $Domain ($Type/$Kind)", "Create domain")) { + return + } - if ($FindMatchingDomain) { - throw "Domain $Domain ($Type/$Kind) already exists on $PiHoleServer! Please use Update-PiHoleDomain to update it" - } + $FindMatchingDomain = Get-PiHoleDomain -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Type $Type -Kind $Kind -Domain $Domain - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $Group) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + if ($FindMatchingDomain) { + throw "Domain $Domain ($Type/$Kind) already exists on $PiHoleServer! Please use Update-PiHoleDomain to update it" + } - $Body = @{ - domain = $Domain - comment = $Comment - groups = [Object[]]($AllGroupsIds) - enabled = $Enabled + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $Group) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id } - - $Params = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Endpoint = "domains/$($Type.ToLower())/$($Kind.ToLower())" - Method = "Post" - IgnoreSsl = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" } + } - $Response = Invoke-PiHoleApiRequest @Params + $Body = @{ + domain = $Domain + comment = $Comment + groups = [Object[]]($AllGroupsIds) + enabled = $Enabled + } - if ($RawOutput) { - Write-Output $Response - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "domains/$($Type.ToLower())/$($Kind.ToLower())" + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - else { - $ObjectFinal = foreach ($Item in $Response.domains) { - [PSCustomObject]@{ - Domain = $Item.domain - Unicode = $Item.unicode - Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() - Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() - Comment = $Item.comment - Groups = $AllGroupsNames - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } + $Response = Invoke-PiHoleApiRequest @Params + + if ($RawOutput) { + Write-Output $Response + } + + else { + $ObjectFinal = foreach ($Item in $Response.domains) { + [PSCustomObject]@{ + Domain = $Item.domain + Unicode = $Item.unicode + Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() + Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() + Comment = $Item.comment + Groups = $AllGroupsNames + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime } - Write-Output $ObjectFinal } + Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 b/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 index 61b98c5..22e9ccd 100644 --- a/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 +++ b/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 @@ -71,77 +71,79 @@ Update-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "you ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole domain $Domain ($Type/$Kind)", "Update domain")) { - if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group') -and -not $PSBoundParameters.ContainsKey('Enabled')) { - throw "To update $Domain, you must specify the Comment, Group, and/or Enabled parameter" - } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole domain $Domain ($Type/$Kind)", "Update domain")) { + return + } - $ExistingDomain = Get-PiHoleDomain -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Type $Type -Kind $Kind -Domain $Domain + if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group') -and -not $PSBoundParameters.ContainsKey('Enabled')) { + throw "To update $Domain, you must specify the Comment, Group, and/or Enabled parameter" + } - if (-not $ExistingDomain) { - throw "Cannot find $Domain of type $Type/$Kind on $PiHoleServer! Please use New-PiHoleDomain to create it" - } + $ExistingDomain = Get-PiHoleDomain -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Type $Type -Kind $Kind -Domain $Domain - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + if (-not $ExistingDomain) { + throw "Cannot find $Domain of type $Type/$Kind on $PiHoleServer! Please use New-PiHoleDomain to create it" + } - $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingDomain.Groups } + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $GroupNamesToResolve) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingDomain.Groups } - # The API replaces the whole domain entry on update, so any property not explicitly - # passed here is resent using the domain's current value to avoid silently clearing it. - # Type/Kind are always resent as-is - see the .DESCRIPTION note on why this never moves - # a domain to a different Type/Kind. - $Body = @{ - type = $Type.ToLower() - kind = $Kind.ToLower() - comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingDomain.Comment } - groups = [Object[]]($AllGroupsIds) - enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $ExistingDomain.Enabled } + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $GroupNamesToResolve) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id } - - $Params = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Endpoint = "domains/$($Type.ToLower())/$($Kind.ToLower())/$([System.Uri]::EscapeDataString($Domain))" - Method = "Put" - IgnoreSsl = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" } + } - $Response = Invoke-PiHoleApiRequest @Params + # The API replaces the whole domain entry on update, so any property not explicitly + # passed here is resent using the domain's current value to avoid silently clearing it. + # Type/Kind are always resent as-is - see the .DESCRIPTION note on why this never moves + # a domain to a different Type/Kind. + $Body = @{ + type = $Type.ToLower() + kind = $Kind.ToLower() + comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingDomain.Comment } + groups = [Object[]]($AllGroupsIds) + enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $ExistingDomain.Enabled } + } - if ($RawOutput) { - Write-Output $Response - } - else { - $ObjectFinal = foreach ($Item in $Response.domains) { - [PSCustomObject]@{ - Domain = $Item.domain - Unicode = $Item.unicode - Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() - Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() - Comment = $Item.comment - Groups = $AllGroupsNames - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "domains/$($Type.ToLower())/$($Kind.ToLower())/$([System.Uri]::EscapeDataString($Domain))" + Method = "Put" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } + + $Response = Invoke-PiHoleApiRequest @Params + + if ($RawOutput) { + Write-Output $Response + } + else { + $ObjectFinal = foreach ($Item in $Response.domains) { + [PSCustomObject]@{ + Domain = $Item.domain + Unicode = $Item.unicode + Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() + Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() + Comment = $Item.comment + Groups = $AllGroupsNames + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime } - Write-Output $ObjectFinal } + Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 b/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 index 649f162..a54ad1f 100644 --- a/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 +++ b/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 @@ -47,48 +47,50 @@ New-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your-ap ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole group $GroupName", "Create group")) { - $GetGroupName = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -GroupName $GroupName + if (-not $PSCmdlet.ShouldProcess("Pi-Hole group $GroupName", "Create group")) { + return + } - if ($GetGroupName) { - Write-Warning -Message "Group $GroupName already exists" - } + $GetGroupName = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -GroupName $GroupName - else { - $Body = @{ - comment = $Comment - enabled = $Enabled - name = $GroupName - } + if ($GetGroupName) { + Write-Warning -Message "Group $GroupName already exists" + } - $Params = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Endpoint = 'groups' - Method = "Post" - IgnoreSsl = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - } + else { + $Body = @{ + comment = $Comment + enabled = $Enabled + name = $GroupName + } - $Response = Invoke-PiHoleApiRequest @Params + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = 'groups' + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - if ($RawOutput) { - Write-Output $Response - } + $Response = Invoke-PiHoleApiRequest @Params - else { - $ObjectFinal = foreach ($Item in $Response.groups) { - [PSCustomObject]@{ - Name = $Item.name - Comment = $Item.comment - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } + if ($RawOutput) { + Write-Output $Response + } + + else { + $ObjectFinal = foreach ($Item in $Response.groups) { + [PSCustomObject]@{ + Name = $Item.name + Comment = $Item.comment + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime } - Write-Output $ObjectFinal } + Write-Output $ObjectFinal } } } diff --git a/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 b/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 index a353905..41a25fe 100644 --- a/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 +++ b/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 @@ -49,52 +49,54 @@ Update-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole group $GroupName", "Update group")) { - $GetGroupName = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -GroupName $GroupName + if (-not $PSCmdlet.ShouldProcess("Pi-Hole group $GroupName", "Update group")) { + return + } - if (-not $GetGroupName) { - throw "Cannot find $GroupName on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } + $GetGroupName = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -GroupName $GroupName - if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Enabled')) { - throw "To update $GroupName, you must specify the Comment and/or Enabled parameter" - } + if (-not $GetGroupName) { + throw "Cannot find $GroupName on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + } - # The API replaces the whole group on update, so any property not explicitly passed - # here is resent using the group's current value to avoid silently clearing it. - $Body = @{ - name = $GroupName - comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $GetGroupName.Comment } - enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $GetGroupName.Enabled } - } + if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Enabled')) { + throw "To update $GroupName, you must specify the Comment and/or Enabled parameter" + } - $Params = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Endpoint = "groups/$GroupName" - Method = "Put" - IgnoreSsl = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 - } + # The API replaces the whole group on update, so any property not explicitly passed + # here is resent using the group's current value to avoid silently clearing it. + $Body = @{ + name = $GroupName + comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $GetGroupName.Comment } + enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $GetGroupName.Enabled } + } + + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "groups/$GroupName" + Method = "Put" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - $Response = Invoke-PiHoleApiRequest @Params + $Response = Invoke-PiHoleApiRequest @Params - if ($RawOutput) { - Write-Output $Response - } - else { - $ObjectFinal = foreach ($Item in $Response.groups) { - [PSCustomObject]@{ - Name = $Item.name - Comment = $Item.comment - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } + if ($RawOutput) { + Write-Output $Response + } + else { + $ObjectFinal = foreach ($Item in $Response.groups) { + [PSCustomObject]@{ + Name = $Item.name + Comment = $Item.comment + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime } - Write-Output $ObjectFinal } + Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 b/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 index 755e430..a1df14c 100644 --- a/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 +++ b/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 @@ -56,83 +56,85 @@ Add-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app [bool]$RawOutput = $false ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole list $Address", "Add list")) { - $FindMatchingList = Get-PiHoleList -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl | Where-Object { $_.Address -eq $Address } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole list $Address", "Add list")) { + return + } - if ($FindMatchingList) { - throw "List $Address already exists on $PiHoleServer! Please use Update-PiHoleList to update the list" - } + $FindMatchingList = Get-PiHoleList -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl | Where-Object { $_.Address -eq $Address } - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $Group) { + if ($FindMatchingList) { + throw "List $Address already exists on $PiHoleServer! Please use Update-PiHoleList to update the list" + } - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - Write-Verbose -Message "Found Group $($FoundGroup.Name) with $($FoundGroup.Id)" - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $Group) { - $Body = @{ - address = $Address - groups = [Object[]]($AllGroupsIds) - comment = $Comment - enabled = $Enabled + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id + Write-Verbose -Message "Found Group $($FoundGroup.Name) with $($FoundGroup.Id)" } - - $Params = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Endpoint = "lists?type=$($Type.ToLower())" - Method = "Post" - IgnoreSsl = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" } + } + + $Body = @{ + address = $Address + groups = [Object[]]($AllGroupsIds) + comment = $Comment + enabled = $Enabled + } - $Response = Invoke-PiHoleApiRequest @Params + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "lists?type=$($Type.ToLower())" + Method = "Post" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } - if ($RawOutput) { - Write-Output $Response - } + $Response = Invoke-PiHoleApiRequest @Params - else { - $ObjectFinal = @() - foreach ($Item in $Response.lists) { - if ($Item.date_updated -eq 0) { - $DateUpdated = $null - } - else { - $DateUpdated = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } - - $Object = [PSCustomObject]@{ - Address = $Item.address - Comment = $Item.comment - Groups = $AllGroupsNames - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() - DateUpdated = $DateUpdated - Number = $Item.number - InvalidDomains = $Item.invalid_domains - AbpEntries = $Item.abp_entries - Status = $Item.status - } - if ($Object) { - $ObjectFinal += $Object - } + if ($RawOutput) { + Write-Output $Response + } + else { + $ObjectFinal = @() + foreach ($Item in $Response.lists) { + if ($Item.date_updated -eq 0) { + $DateUpdated = $null } - Write-Output $ObjectFinal + else { + $DateUpdated = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } + + $Object = [PSCustomObject]@{ + Address = $Item.address + Comment = $Item.comment + Groups = $AllGroupsNames + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() + DateUpdated = $DateUpdated + Number = $Item.number + InvalidDomains = $Item.invalid_domains + AbpEntries = $Item.abp_entries + Status = $Item.status + } + if ($Object) { + $ObjectFinal += $Object + } + } + Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 b/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 index cd1740d..a310a2a 100644 --- a/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 +++ b/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 @@ -59,83 +59,85 @@ Update-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your- ) try { - if ($PSCmdlet.ShouldProcess("Pi-Hole list $Address", "Update list")) { - if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group') -and -not $PSBoundParameters.ContainsKey('Enabled')) { - throw "To update $Address, you must specify the Comment, Group, and/or Enabled parameter" - } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole list $Address", "Update list")) { + return + } - $ExistingList = Get-PiHoleList -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -List $Address | Where-Object { $_.Type -eq $Type } + if (-not $PSBoundParameters.ContainsKey('Comment') -and -not $PSBoundParameters.ContainsKey('Group') -and -not $PSBoundParameters.ContainsKey('Enabled')) { + throw "To update $Address, you must specify the Comment, Group, and/or Enabled parameter" + } - if (-not $ExistingList) { - throw "Cannot find $Address of type $Type on $PiHoleServer! Please use Add-PiHoleList to create it" - } + $ExistingList = Get-PiHoleList -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -List $Address | Where-Object { $_.Type -eq $Type } - $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl + if (-not $ExistingList) { + throw "Cannot find $Address of type $Type on $PiHoleServer! Please use Add-PiHoleList to create it" + } - $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingList.Groups } + $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $GroupNamesToResolve) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingList.Groups } - # The API replaces the whole list on update, so any property not explicitly passed here - # is resent using the list's current value to avoid silently clearing it. - $Body = @{ - comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingList.Comment } - groups = [Object[]]($AllGroupsIds) - enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $ExistingList.Enabled } + $AllGroupsNames = @() + $AllGroupsIds = @() + foreach ($GroupItem in $GroupNamesToResolve) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $AllGroupsNames += $FoundGroup.Name + $AllGroupsIds += $FoundGroup.Id } - - $Params = @{ - PiHoleServer = $PiHoleServer - Password = $Password - Endpoint = "lists/$Address`?type=$($Type.ToLower())" - Method = "Put" - IgnoreSsl = $IgnoreSsl - Body = $Body | ConvertTo-Json -Depth 10 + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" } + } - $Response = Invoke-PiHoleApiRequest @Params + # The API replaces the whole list on update, so any property not explicitly passed here + # is resent using the list's current value to avoid silently clearing it. + $Body = @{ + comment = if ($PSBoundParameters.ContainsKey('Comment')) { $Comment } else { $ExistingList.Comment } + groups = [Object[]]($AllGroupsIds) + enabled = if ($PSBoundParameters.ContainsKey('Enabled')) { $Enabled } else { $ExistingList.Enabled } + } - if ($RawOutput) { - Write-Output $Response - } - else { - $ObjectFinal = foreach ($Item in $Response.lists) { - if ($Item.date_updated -eq 0) { - $DateUpdated = $null - } - else { - $DateUpdated = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } - - [PSCustomObject]@{ - Address = $Item.address - Comment = $Item.comment - Groups = $AllGroupsNames - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() - DateUpdated = $DateUpdated - Number = $Item.number - InvalidDomains = $Item.invalid_domains - AbpEntries = $Item.abp_entries - Status = $Item.status - } + $Params = @{ + PiHoleServer = $PiHoleServer + Password = $Password + Endpoint = "lists/$Address`?type=$($Type.ToLower())" + Method = "Put" + IgnoreSsl = $IgnoreSsl + Body = $Body | ConvertTo-Json -Depth 10 + } + + $Response = Invoke-PiHoleApiRequest @Params + + if ($RawOutput) { + Write-Output $Response + } + else { + $ObjectFinal = foreach ($Item in $Response.lists) { + if ($Item.date_updated -eq 0) { + $DateUpdated = $null + } + else { + $DateUpdated = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } + + [PSCustomObject]@{ + Address = $Item.address + Comment = $Item.comment + Groups = $AllGroupsNames + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() + DateUpdated = $DateUpdated + Number = $Item.number + InvalidDomains = $Item.invalid_domains + AbpEntries = $Item.abp_entries + Status = $Item.status } - Write-Output $ObjectFinal } + Write-Output $ObjectFinal } } From c6b01bc39b443d331213f2bccb4b82f8a89c3d5f Mon Sep 17 00:00:00 2001 From: Mike Madeja Date: Sat, 7 Nov 2026 07:54:22 -0600 Subject: [PATCH 3/5] refactor: share the bodies of near-identical functions via private helpers SonarCloud's new-code duplication gate failed (19.8%, limit 3%) because several function families were already copies of each other, differing only in endpoint and property names. Move their shared bodies into private helpers: - Invoke-PiHoleAction: Invoke-PiHoleFlushLogs, Invoke-PiHoleFlushNetwork, Restart-PiHoleDnsService - Get-PiHoleLogContent: Get-PiHoleLogDnsmasq, Get-PiHoleLogFtl, Get-PiHoleLogWebserver - Get-PiHoleNetworkInfo: Get-PiHoleNetworkGateway, -Interface, -Route - Resolve-PiHoleGroupName: the group lookup in New-/Update-PiHoleClient, New-/Update-PiHoleDomain, Add-/Update-PiHoleList - ConvertTo-PiHoleClientObject, -DomainObject, -GroupObject: output of the client, domain and group New/Update functions Public names, parameters and output are unchanged; comparing develop and this branch against a fake API gave identical output and requests for all 20 scenarios tried. Co-Authored-By: Claude Opus 5.5 --- PiHoleShell/Private/Get-PiHoleLogContent.ps1 | 52 +++++++++ PiHoleShell/Private/Get-PiHoleNetworkInfo.ps1 | 41 +++++++ PiHoleShell/Private/Invoke-PiHoleAction.ps1 | 40 +++++++ PiHoleShell/Private/ManagementHelpers.ps1 | 101 ++++++++++++++++++ .../Public/Actions/Invoke-PiHoleFlushLogs.ps1 | 22 +--- .../Actions/Invoke-PiHoleFlushNetwork.ps1 | 22 +--- .../Actions/Restart-PiHoleDnsService.ps1 | 22 +--- .../ClientManagement/New-PiHoleClient.ps1 | 27 +---- .../ClientManagement/Update-PiHoleClient.ps1 | 27 +---- .../DomainManagement/New-PiHoleDomain.ps1 | 30 +----- .../DomainManagement/Update-PiHoleDomain.ps1 | 30 +----- .../FTLInformation/Get-PiHoleLogDnsmasq.ps1 | 35 +----- .../FTLInformation/Get-PiHoleLogFtl.ps1 | 35 +----- .../FTLInformation/Get-PiHoleLogWebserver.ps1 | 35 +----- .../GroupManagement/New-PiHoleGroup.ps1 | 11 +- .../GroupManagement/Update-PiHoleGroup.ps1 | 11 +- .../Public/ListManagement/Add-PiHoleList.ps1 | 17 +-- .../ListManagement/Update-PiHoleList.ps1 | 15 +-- .../Get-PiHoleNetworkGateway.ps1 | 21 +--- .../Get-PiHoleNetworkInterface.ps1 | 21 +--- .../Get-PiHoleNetworkRoute.ps1 | 21 +--- 21 files changed, 273 insertions(+), 363 deletions(-) create mode 100644 PiHoleShell/Private/Get-PiHoleLogContent.ps1 create mode 100644 PiHoleShell/Private/Get-PiHoleNetworkInfo.ps1 create mode 100644 PiHoleShell/Private/Invoke-PiHoleAction.ps1 create mode 100644 PiHoleShell/Private/ManagementHelpers.ps1 diff --git a/PiHoleShell/Private/Get-PiHoleLogContent.ps1 b/PiHoleShell/Private/Get-PiHoleLogContent.ps1 new file mode 100644 index 0000000..417edfb --- /dev/null +++ b/PiHoleShell/Private/Get-PiHoleLogContent.ps1 @@ -0,0 +1,52 @@ +function Get-PiHoleLogContent { + #INTERNAL FUNCTION + # + # Shared body of Get-PiHoleLogDnsmasq, Get-PiHoleLogFtl and Get-PiHoleLogWebserver: the three + # /logs/* endpoints take the same nextID parameter and return the same shape. + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [System.URI]$PiHoleServer, + [Parameter(Mandatory = $true)] + [string]$Password, + [Parameter(Mandatory = $true)] + [string]$Endpoint, + [Nullable[int]]$NextID, + [bool]$IgnoreSsl = $false, + [bool]$RawOutput = $false + ) + try { + if ($null -ne $NextID) { + $Endpoint += "?nextID=$NextID" + } + + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint + + if ($RawOutput) { + Write-Output $Response + } + + else { + $Log = foreach ($Item in $Response.log) { + [PSCustomObject]@{ + Timestamp = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.timestamp).LocalTime + Message = $Item.message + Priority = $Item.prio + } + } + + $Object = [PSCustomObject]@{ + Log = $Log + NextID = $Response.nextID + Pid = $Response.pid + File = $Response.file + } + Write-Output $Object + } + } + + catch { + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) + } +} diff --git a/PiHoleShell/Private/Get-PiHoleNetworkInfo.ps1 b/PiHoleShell/Private/Get-PiHoleNetworkInfo.ps1 new file mode 100644 index 0000000..90988e8 --- /dev/null +++ b/PiHoleShell/Private/Get-PiHoleNetworkInfo.ps1 @@ -0,0 +1,41 @@ +function Get-PiHoleNetworkInfo { + #INTERNAL FUNCTION + # + # Shared body of Get-PiHoleNetworkGateway, Get-PiHoleNetworkInterface and + # Get-PiHoleNetworkRoute: each /network/* endpoint takes the same detailed parameter and + # returns its data under one property (Property), converted to PascalCase as-is. + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [System.URI]$PiHoleServer, + [Parameter(Mandatory = $true)] + [string]$Password, + [Parameter(Mandatory = $true)] + [string]$Endpoint, + [Parameter(Mandatory = $true)] + [string]$Property, + [Nullable[bool]]$Detailed, + [bool]$IgnoreSsl = $false, + [bool]$RawOutput = $false + ) + try { + if ($null -ne $Detailed) { + $Endpoint += "?detailed=$($Detailed.ToString().ToLower())" + } + + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint + + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = ConvertTo-PiHolePascalCaseObject -InputObject $Response.$Property + Write-Output $Object + } + } + + catch { + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) + } +} diff --git a/PiHoleShell/Private/Invoke-PiHoleAction.ps1 b/PiHoleShell/Private/Invoke-PiHoleAction.ps1 new file mode 100644 index 0000000..cabad6e --- /dev/null +++ b/PiHoleShell/Private/Invoke-PiHoleAction.ps1 @@ -0,0 +1,40 @@ +function Invoke-PiHoleAction { + #INTERNAL FUNCTION + # + # Shared body of the parameterless POST /action/* functions (Invoke-PiHoleFlushLogs, + # Invoke-PiHoleFlushNetwork, Restart-PiHoleDnsService), which differ only in their endpoint + # and the Status they report. Callers do their own ShouldProcess check first. + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Every caller checks ShouldProcess before calling this")] + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [System.URI]$PiHoleServer, + [Parameter(Mandatory = $true)] + [string]$Password, + [Parameter(Mandatory = $true)] + [string]$Endpoint, + [Parameter(Mandatory = $true)] + [string]$Status, + [bool]$IgnoreSsl = $false, + [bool]$RawOutput = $false + ) + + try { + $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint -Method Post + + if ($RawOutput) { + Write-Output $Response + } + else { + $Object = [PSCustomObject]@{ + Status = $Status + } + Write-Output $Object + } + } + + catch { + Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) + } +} diff --git a/PiHoleShell/Private/ManagementHelpers.ps1 b/PiHoleShell/Private/ManagementHelpers.ps1 new file mode 100644 index 0000000..99b792e --- /dev/null +++ b/PiHoleShell/Private/ManagementHelpers.ps1 @@ -0,0 +1,101 @@ +function Resolve-PiHoleGroupName { + #INTERNAL FUNCTION + # + # Maps group names to the group IDs the client/domain/list APIs expect, throwing on the first + # name that doesn't exist. AllGroups is the caller's Get-PiHoleGroup result, so a function + # resolving groups only fetches them once. + param ( + [Parameter(Mandatory = $true)] + [System.URI]$PiHoleServer, + $AllGroups, + $Name + ) + + $Names = @() + $Ids = @() + foreach ($GroupItem in $Name) { + $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } + if ($FoundGroup) { + $Names += $FoundGroup.Name + $Ids += $FoundGroup.Id + Write-Verbose -Message "Found Group $($FoundGroup.Name) with $($FoundGroup.Id)" + } + else { + throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" + } + } + + [PSCustomObject]@{ + Names = $Names + Ids = $Ids + } +} + +function ConvertTo-PiHoleClientObject { + #INTERNAL FUNCTION + # + # Formats the clients in a New-/Update-PiHoleClient response. Groups is passed in rather than + # read from the response, which only has group IDs. + param ( + $Client, + $Groups + ) + + foreach ($Item in $Client) { + [PSCustomObject]@{ + Client = $Item.client + Name = $Item.name + Comment = $Item.comment + Groups = $Groups + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } + } +} + +function ConvertTo-PiHoleDomainObject { + #INTERNAL FUNCTION + # + # Formats the domains in a New-/Update-PiHoleDomain response. Groups is passed in rather than + # read from the response, which only has group IDs. + param ( + $Domain, + $Groups + ) + + foreach ($Item in $Domain) { + [PSCustomObject]@{ + Domain = $Item.domain + Unicode = $Item.unicode + Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() + Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() + Comment = $Item.comment + Groups = $Groups + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } + } +} + +function ConvertTo-PiHoleGroupObject { + #INTERNAL FUNCTION + # + # Formats the groups in a New-/Update-PiHoleGroup response. + param ( + $Group + ) + + foreach ($Item in $Group) { + [PSCustomObject]@{ + Name = $Item.name + Comment = $Item.comment + Enabled = $Item.enabled + Id = $Item.id + DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime + DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime + } + } +} diff --git a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 index 1d49718..7cc0759 100644 --- a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 +++ b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 @@ -34,25 +34,9 @@ Invoke-PiHoleFlushLogs -PiHoleServer "http://pihole.domain.com:8080" -Password " [bool]$RawOutput = $false ) - try { - if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush DNS logs")) { - return - } - - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/flush/logs' -Method Post - - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Status = "Flushed" - } - Write-Output $Object - } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush DNS logs")) { + return } - catch { - Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) - } + Invoke-PiHoleAction -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'action/flush/logs' -Status 'Flushed' } diff --git a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 index 27a279b..63bf810 100644 --- a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 +++ b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 @@ -32,25 +32,9 @@ Invoke-PiHoleFlushNetwork -PiHoleServer "http://pihole.domain.com:8080" -Passwor [bool]$RawOutput = $false ) - try { - if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush network table")) { - return - } - - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/flush/network' -Method Post - - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Status = "Flushed" - } - Write-Output $Object - } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush network table")) { + return } - catch { - Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) - } + Invoke-PiHoleAction -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'action/flush/network' -Status 'Flushed' } \ No newline at end of file diff --git a/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 b/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 index 2a34d3a..ef20ae8 100644 --- a/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 +++ b/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 @@ -32,25 +32,9 @@ Invoke-PiHoleRestartDns -PiHoleServer "http://pihole.domain.com:8080" -Password [bool]$RawOutput = $false ) - try { - if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Restart DNS service")) { - return - } - - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint 'action/restartdns' -Method Post - - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = [PSCustomObject]@{ - Status = "Restarted" - } - Write-Output $Object - } + if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Restart DNS service")) { + return } - catch { - Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) - } + Invoke-PiHoleAction -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'action/restartdns' -Status 'Restarted' } \ No newline at end of file diff --git a/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 b/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 index 76d6e09..dc05a38 100644 --- a/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 +++ b/PiHoleShell/Public/ClientManagement/New-PiHoleClient.ps1 @@ -60,18 +60,9 @@ New-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a } $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $Group) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + $ResolvedGroups = Resolve-PiHoleGroupName -PiHoleServer $PiHoleServer -AllGroups $AllGroups -Name $Group + $AllGroupsNames = $ResolvedGroups.Names + $AllGroupsIds = $ResolvedGroups.Ids $Body = @{ client = $Client @@ -95,17 +86,7 @@ New-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a } else { - $ObjectFinal = foreach ($Item in $Response.clients) { - [PSCustomObject]@{ - Client = $Item.client - Name = $Item.name - Comment = $Item.comment - Groups = $AllGroupsNames - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } - } + $ObjectFinal = ConvertTo-PiHoleClientObject -Client $Response.clients -Groups $AllGroupsNames Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 b/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 index 04cea28..75828b4 100644 --- a/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 +++ b/PiHoleShell/Public/ClientManagement/Update-PiHoleClient.ps1 @@ -68,18 +68,9 @@ Update-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "you $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingClient.Groups } - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $GroupNamesToResolve) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + $ResolvedGroups = Resolve-PiHoleGroupName -PiHoleServer $PiHoleServer -AllGroups $AllGroups -Name $GroupNamesToResolve + $AllGroupsNames = $ResolvedGroups.Names + $AllGroupsIds = $ResolvedGroups.Ids # The API replaces the whole client entry on update, so any property not explicitly # passed here is resent using the client's current value to avoid silently clearing it. @@ -103,17 +94,7 @@ Update-PiHoleClient -PiHoleServer "http://pihole.domain.com:8080" -Password "you Write-Output $Response } else { - $ObjectFinal = foreach ($Item in $Response.clients) { - [PSCustomObject]@{ - Client = $Item.client - Name = $Item.name - Comment = $Item.comment - Groups = $AllGroupsNames - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } - } + $ObjectFinal = ConvertTo-PiHoleClientObject -Client $Response.clients -Groups $AllGroupsNames Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 b/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 index c466675..473c4c7 100644 --- a/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 +++ b/PiHoleShell/Public/DomainManagement/New-PiHoleDomain.ps1 @@ -74,18 +74,9 @@ New-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a } $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $Group) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + $ResolvedGroups = Resolve-PiHoleGroupName -PiHoleServer $PiHoleServer -AllGroups $AllGroups -Name $Group + $AllGroupsNames = $ResolvedGroups.Names + $AllGroupsIds = $ResolvedGroups.Ids $Body = @{ domain = $Domain @@ -110,20 +101,7 @@ New-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a } else { - $ObjectFinal = foreach ($Item in $Response.domains) { - [PSCustomObject]@{ - Domain = $Item.domain - Unicode = $Item.unicode - Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() - Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() - Comment = $Item.comment - Groups = $AllGroupsNames - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } - } + $ObjectFinal = ConvertTo-PiHoleDomainObject -Domain $Response.domains -Groups $AllGroupsNames Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 b/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 index 22e9ccd..6999292 100644 --- a/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 +++ b/PiHoleShell/Public/DomainManagement/Update-PiHoleDomain.ps1 @@ -89,18 +89,9 @@ Update-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "you $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingDomain.Groups } - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $GroupNamesToResolve) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + $ResolvedGroups = Resolve-PiHoleGroupName -PiHoleServer $PiHoleServer -AllGroups $AllGroups -Name $GroupNamesToResolve + $AllGroupsNames = $ResolvedGroups.Names + $AllGroupsIds = $ResolvedGroups.Ids # The API replaces the whole domain entry on update, so any property not explicitly # passed here is resent using the domain's current value to avoid silently clearing it. @@ -129,20 +120,7 @@ Update-PiHoleDomain -PiHoleServer "http://pihole.domain.com:8080" -Password "you Write-Output $Response } else { - $ObjectFinal = foreach ($Item in $Response.domains) { - [PSCustomObject]@{ - Domain = $Item.domain - Unicode = $Item.unicode - Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower() - Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower() - Comment = $Item.comment - Groups = $AllGroupsNames - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } - } + $ObjectFinal = ConvertTo-PiHoleDomainObject -Domain $Response.domains -Groups $AllGroupsNames Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogDnsmasq.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogDnsmasq.ps1 index 059f6be..f36d439 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogDnsmasq.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogDnsmasq.ps1 @@ -38,38 +38,5 @@ Get-PiHoleLogDnsmasq -PiHoleServer "http://pihole.domain.com:8080" -Password "yo [bool]$IgnoreSsl = $false, [bool]$RawOutput = $false ) - try { - $Endpoint = 'logs/dnsmasq' - if ($PSBoundParameters.ContainsKey('NextID')) { - $Endpoint += "?nextID=$NextID" - } - - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint - - if ($RawOutput) { - Write-Output $Response - } - - else { - $Log = foreach ($Item in $Response.log) { - [PSCustomObject]@{ - Timestamp = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.timestamp).LocalTime - Message = $Item.message - Priority = $Item.prio - } - } - - $Object = [PSCustomObject]@{ - Log = $Log - NextID = $Response.nextID - Pid = $Response.pid - File = $Response.file - } - Write-Output $Object - } - } - - catch { - Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) - } + Get-PiHoleLogContent -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'logs/dnsmasq' -NextID $NextID } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogFtl.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogFtl.ps1 index 2096fae..082781e 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogFtl.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogFtl.ps1 @@ -38,38 +38,5 @@ Get-PiHoleLogFtl -PiHoleServer "http://pihole.domain.com:8080" -Password "your-a [bool]$IgnoreSsl = $false, [bool]$RawOutput = $false ) - try { - $Endpoint = 'logs/ftl' - if ($PSBoundParameters.ContainsKey('NextID')) { - $Endpoint += "?nextID=$NextID" - } - - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint - - if ($RawOutput) { - Write-Output $Response - } - - else { - $Log = foreach ($Item in $Response.log) { - [PSCustomObject]@{ - Timestamp = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.timestamp).LocalTime - Message = $Item.message - Priority = $Item.prio - } - } - - $Object = [PSCustomObject]@{ - Log = $Log - NextID = $Response.nextID - Pid = $Response.pid - File = $Response.file - } - Write-Output $Object - } - } - - catch { - Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) - } + Get-PiHoleLogContent -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'logs/ftl' -NextID $NextID } diff --git a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogWebserver.ps1 b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogWebserver.ps1 index b9946a6..b84bf3d 100644 --- a/PiHoleShell/Public/FTLInformation/Get-PiHoleLogWebserver.ps1 +++ b/PiHoleShell/Public/FTLInformation/Get-PiHoleLogWebserver.ps1 @@ -38,38 +38,5 @@ Get-PiHoleLogWebserver -PiHoleServer "http://pihole.domain.com:8080" -Password " [bool]$IgnoreSsl = $false, [bool]$RawOutput = $false ) - try { - $Endpoint = 'logs/webserver' - if ($PSBoundParameters.ContainsKey('NextID')) { - $Endpoint += "?nextID=$NextID" - } - - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint - - if ($RawOutput) { - Write-Output $Response - } - - else { - $Log = foreach ($Item in $Response.log) { - [PSCustomObject]@{ - Timestamp = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.timestamp).LocalTime - Message = $Item.message - Priority = $Item.prio - } - } - - $Object = [PSCustomObject]@{ - Log = $Log - NextID = $Response.nextID - Pid = $Response.pid - File = $Response.file - } - Write-Output $Object - } - } - - catch { - Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) - } + Get-PiHoleLogContent -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'logs/webserver' -NextID $NextID } diff --git a/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 b/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 index a54ad1f..9df8f76 100644 --- a/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 +++ b/PiHoleShell/Public/GroupManagement/New-PiHoleGroup.ps1 @@ -80,16 +80,7 @@ New-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your-ap } else { - $ObjectFinal = foreach ($Item in $Response.groups) { - [PSCustomObject]@{ - Name = $Item.name - Comment = $Item.comment - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } - } + $ObjectFinal = ConvertTo-PiHoleGroupObject -Group $Response.groups Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 b/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 index 41a25fe..3ad120f 100644 --- a/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 +++ b/PiHoleShell/Public/GroupManagement/Update-PiHoleGroup.ps1 @@ -86,16 +86,7 @@ Update-PiHoleGroup -PiHoleServer "http://pihole.domain.com:8080" -Password "your Write-Output $Response } else { - $ObjectFinal = foreach ($Item in $Response.groups) { - [PSCustomObject]@{ - Name = $Item.name - Comment = $Item.comment - Enabled = $Item.enabled - Id = $Item.id - DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime - DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime - } - } + $ObjectFinal = ConvertTo-PiHoleGroupObject -Group $Response.groups Write-Output $ObjectFinal } } diff --git a/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 b/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 index a1df14c..ef8b23c 100644 --- a/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 +++ b/PiHoleShell/Public/ListManagement/Add-PiHoleList.ps1 @@ -67,20 +67,9 @@ Add-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app } $AllGroups = Get-PiHoleGroup -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $Group) { - - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - Write-Verbose -Message "Found Group $($FoundGroup.Name) with $($FoundGroup.Id)" - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + $ResolvedGroups = Resolve-PiHoleGroupName -PiHoleServer $PiHoleServer -AllGroups $AllGroups -Name $Group + $AllGroupsNames = $ResolvedGroups.Names + $AllGroupsIds = $ResolvedGroups.Ids $Body = @{ address = $Address diff --git a/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 b/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 index a310a2a..fb66bf2 100644 --- a/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 +++ b/PiHoleShell/Public/ListManagement/Update-PiHoleList.ps1 @@ -77,18 +77,9 @@ Update-PiHoleList -PiHoleServer "http://pihole.domain.com:8080" -Password "your- $GroupNamesToResolve = if ($PSBoundParameters.ContainsKey('Group')) { $Group } else { $ExistingList.Groups } - $AllGroupsNames = @() - $AllGroupsIds = @() - foreach ($GroupItem in $GroupNamesToResolve) { - $FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem } - if ($FoundGroup) { - $AllGroupsNames += $FoundGroup.Name - $AllGroupsIds += $FoundGroup.Id - } - else { - throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups" - } - } + $ResolvedGroups = Resolve-PiHoleGroupName -PiHoleServer $PiHoleServer -AllGroups $AllGroups -Name $GroupNamesToResolve + $AllGroupsNames = $ResolvedGroups.Names + $AllGroupsIds = $ResolvedGroups.Ids # The API replaces the whole list on update, so any property not explicitly passed here # is resent using the list's current value to avoid silently clearing it. diff --git a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkGateway.ps1 b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkGateway.ps1 index 9c7ac31..9539dc0 100644 --- a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkGateway.ps1 +++ b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkGateway.ps1 @@ -38,24 +38,5 @@ Get-PiHoleNetworkGateway -PiHoleServer "http://pihole.domain.com:8080" -Password [bool]$IgnoreSsl = $false, [bool]$RawOutput = $false ) - try { - $Endpoint = 'network/gateway' - if ($PSBoundParameters.ContainsKey('Detailed')) { - $Endpoint += "?detailed=$($Detailed.ToString().ToLower())" - } - - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint - - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = ConvertTo-PiHolePascalCaseObject -InputObject $Response.gateway - Write-Output $Object - } - } - - catch { - Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) - } + Get-PiHoleNetworkInfo -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'network/gateway' -Property 'gateway' -Detailed $Detailed } diff --git a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkInterface.ps1 b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkInterface.ps1 index 04679f6..a3dc5cf 100644 --- a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkInterface.ps1 +++ b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkInterface.ps1 @@ -38,24 +38,5 @@ Get-PiHoleNetworkInterface -PiHoleServer "http://pihole.domain.com:8080" -Passwo [bool]$IgnoreSsl = $false, [bool]$RawOutput = $false ) - try { - $Endpoint = 'network/interfaces' - if ($PSBoundParameters.ContainsKey('Detailed')) { - $Endpoint += "?detailed=$($Detailed.ToString().ToLower())" - } - - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint - - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = ConvertTo-PiHolePascalCaseObject -InputObject $Response.interfaces - Write-Output $Object - } - } - - catch { - Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) - } + Get-PiHoleNetworkInfo -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'network/interfaces' -Property 'interfaces' -Detailed $Detailed } diff --git a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkRoute.ps1 b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkRoute.ps1 index 4373d6f..532d78d 100644 --- a/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkRoute.ps1 +++ b/PiHoleShell/Public/NetworkInformation/Get-PiHoleNetworkRoute.ps1 @@ -38,24 +38,5 @@ Get-PiHoleNetworkRoute -PiHoleServer "http://pihole.domain.com:8080" -Password " [bool]$IgnoreSsl = $false, [bool]$RawOutput = $false ) - try { - $Endpoint = 'network/routes' - if ($PSBoundParameters.ContainsKey('Detailed')) { - $Endpoint += "?detailed=$($Detailed.ToString().ToLower())" - } - - $Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint - - if ($RawOutput) { - Write-Output $Response - } - else { - $Object = ConvertTo-PiHolePascalCaseObject -InputObject $Response.routes - Write-Output $Object - } - } - - catch { - Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_) - } + Get-PiHoleNetworkInfo -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'network/routes' -Property 'routes' -Detailed $Detailed } From 2636a4ae0d8f0ec4e4d65a04ad61b54a883acab3 Mon Sep 17 00:00:00 2001 From: Mike Madeja Date: Sat, 7 Nov 2026 07:55:43 -0600 Subject: [PATCH 4/5] refactor: call Invoke-PiHoleAction inside the ShouldProcess check The action wrappers have a single statement, so an if block reads better than an early return. It also keeps Invoke-PiHoleFlushNetwork and Restart-PiHoleDnsService under SonarCloud's duplicate-block size. Co-Authored-By: Claude Opus 5.5 --- PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 | 6 ++---- PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 | 6 ++---- PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 | 6 ++---- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 index 7cc0759..ebf462c 100644 --- a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 +++ b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1 @@ -34,9 +34,7 @@ Invoke-PiHoleFlushLogs -PiHoleServer "http://pihole.domain.com:8080" -Password " [bool]$RawOutput = $false ) - if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush DNS logs")) { - return + if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush DNS logs")) { + Invoke-PiHoleAction -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'action/flush/logs' -Status 'Flushed' } - - Invoke-PiHoleAction -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'action/flush/logs' -Status 'Flushed' } diff --git a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 index 63bf810..ca01809 100644 --- a/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 +++ b/PiHoleShell/Public/Actions/Invoke-PiHoleFlushNetwork.ps1 @@ -32,9 +32,7 @@ Invoke-PiHoleFlushNetwork -PiHoleServer "http://pihole.domain.com:8080" -Passwor [bool]$RawOutput = $false ) - if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush network table")) { - return + if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush network table")) { + Invoke-PiHoleAction -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'action/flush/network' -Status 'Flushed' } - - Invoke-PiHoleAction -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'action/flush/network' -Status 'Flushed' } \ No newline at end of file diff --git a/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 b/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 index ef20ae8..872e15e 100644 --- a/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 +++ b/PiHoleShell/Public/Actions/Restart-PiHoleDnsService.ps1 @@ -32,9 +32,7 @@ Invoke-PiHoleRestartDns -PiHoleServer "http://pihole.domain.com:8080" -Password [bool]$RawOutput = $false ) - if (-not $PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Restart DNS service")) { - return + if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Restart DNS service")) { + Invoke-PiHoleAction -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'action/restartdns' -Status 'Restarted' } - - Invoke-PiHoleAction -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'action/restartdns' -Status 'Restarted' } \ No newline at end of file From 61286ffee005b24b4252e7436196e2e45e9d22c0 Mon Sep 17 00:00:00 2001 From: Mike Madeja Date: Sat, 7 Nov 2026 08:24:34 -0600 Subject: [PATCH 5/5] test: cover Invoke-PiHoleApiRequest's login, request and logout order Unit test with only Invoke-RestMethod mocked, so the real login and logout run. Checks that a call logs in, sends the request with that session and then logs out, in that order; that the session is still closed when the request fails; that a failed login sends nothing else; and that Body/Form are passed through. Co-Authored-By: Claude Opus 5.5 --- .../Private/Invoke-PiHoleApiRequest.Tests.ps1 | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 tests/Private/Invoke-PiHoleApiRequest.Tests.ps1 diff --git a/tests/Private/Invoke-PiHoleApiRequest.Tests.ps1 b/tests/Private/Invoke-PiHoleApiRequest.Tests.ps1 new file mode 100644 index 0000000..ba621ec --- /dev/null +++ b/tests/Private/Invoke-PiHoleApiRequest.Tests.ps1 @@ -0,0 +1,78 @@ +# Requires -Module Pester +Describe 'Invoke-PiHoleApiRequest' { + BeforeAll { + # Dot-sourced directly with the real login (Request-PiHoleAuth) and logout + # (Remove-PiHoleCurrentAuthSession, in Misc.ps1), so only the HTTP layer is mocked and the + # tests see the actual order of login, request and logout. + . .\PiHoleShell\Private\Invoke-PiHoleApiRequest.ps1 + . .\PiHoleShell\Private\Misc.ps1 + . .\PiHoleShell\Public\Authentication\Request-PiHoleAuth.ps1 + + $server = [uri]'http://pihole.local' + } + + BeforeEach { + # Every HTTP call is recorded as " sid=", in the order it was made. + $script:Calls = [System.Collections.Generic.List[string]]::new() + $script:LoginFails = $false + $script:RequestFails = $false + + Mock -CommandName Invoke-RestMethod -MockWith { + $path = ([string]$Uri) -replace '^http://pihole\.local/api/', '' + $script:Calls.Add("$Method $path sid=$($Headers.sid)") + + if ($path -eq 'auth' -and $Method -eq 'Post') { + if ($script:LoginFails) { throw 'Unauthorized' } + return @{ session = @{ sid = 'test-sid' } } + } + if ($path -eq 'auth') { + return + } + if ($script:RequestFails) { throw 'Request failed' } + return @{ version = 'v6' } + } + } + + It 'logs in, sends the request with that session, then logs out - in that order' { + $result = Invoke-PiHoleApiRequest -PiHoleServer $server -Password 'pw' -Endpoint 'info/version' + + $result.version | Should -Be 'v6' + $script:Calls | Should -Be @( + 'Post auth sid=' + 'Get info/version sid=test-sid' + 'Delete auth sid=test-sid' + ) + } + + It 'still logs out when the request fails, and passes the error on' { + $script:RequestFails = $true + + { Invoke-PiHoleApiRequest -PiHoleServer $server -Password 'pw' -Endpoint 'info/version' } | Should -Throw 'Request failed' + + $script:Calls | Should -Be @( + 'Post auth sid=' + 'Get info/version sid=test-sid' + 'Delete auth sid=test-sid' + ) + } + + It 'stops after a failed login, without sending the request or a logout' { + $script:LoginFails = $true + + { Invoke-PiHoleApiRequest -PiHoleServer $server -Password 'wrong' -Endpoint 'info/version' } | Should -Throw 'Unauthorized' + + $script:Calls | Should -Be @('Post auth sid=') + } + + It 'passes Method and Body through, and leaves ContentType off a Form upload' { + Invoke-PiHoleApiRequest -PiHoleServer $server -Password 'pw' -Endpoint 'groups' -Method 'Post' -Body '{"name":"g"}' | Out-Null + Should -Invoke Invoke-RestMethod -Times 1 -Exactly -ParameterFilter { + $Method -eq 'Post' -and $Body -eq '{"name":"g"}' -and $ContentType -eq 'application/json' + } + + Invoke-PiHoleApiRequest -PiHoleServer $server -Password 'pw' -Endpoint 'teleporter' -Method 'Post' -Form @{ file = 'x' } | Out-Null + Should -Invoke Invoke-RestMethod -Times 1 -Exactly -ParameterFilter { + $Form.file -eq 'x' -and -not $ContentType + } + } +}