Initial commit. Working and linked on PSGallery

This commit is contained in:
2026-05-15 08:53:21 +08:00
commit 7c77363885
17 changed files with 1109 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
function Invoke-UnifiRequest {
[CmdletBinding()]
param(
[ValidateSet('GET', 'POST', 'PUT', 'DELETE')]
[string]$Method = 'GET',
# For site-scoped endpoints pass just the path after /api/s/{site}, e.g. '/rest/wlanconf'
# For global endpoints pass the full path, e.g. '/api/self/sites'
[Parameter(Mandatory)]
[string]$Endpoint,
[string]$Site,
[object]$Body
)
if (-not $script:UnifiSession -or -not $script:UnifiConfig) {
throw "Not connected. Run Connect-UnifiController first."
}
$baseUrl = $script:UnifiConfig.ControllerUrl
$uri = if ($Site) {
"$baseUrl/api/s/$Site$Endpoint"
} else {
"$baseUrl$Endpoint"
}
$params = @{
Method = $Method
Uri = $uri
WebSession = $script:UnifiSession
}
if ($script:UnifiConfig.SkipCertificateCheck) {
$params.SkipCertificateCheck = $true
}
if ($Method -ne 'GET' -and $script:UnifiConfig.CsrfToken) {
$params.Headers = @{ 'X-Csrf-Token' = $script:UnifiConfig.CsrfToken }
}
if ($Body) {
$params.Body = ($Body | ConvertTo-Json -Depth 10 -Compress)
$params.ContentType = 'application/json'
}
try {
Invoke-RestMethod @params
}
catch [Microsoft.PowerShell.Commands.HttpResponseException] {
$code = $_.Exception.Response.StatusCode.value__
if ($code -eq 401) {
throw "Session expired or unauthorized. Run Connect-UnifiController to re-authenticate."
}
throw "HTTP $code`: $_"
}
}

View File

@@ -0,0 +1,6 @@
function Resolve-UnifiSite {
param([string]$Site)
if ($Site) { return $Site }
if ($script:UnifiConfig.DefaultSite) { return $script:UnifiConfig.DefaultSite }
return 'default'
}

31
Private/UnifiConfig.ps1 Normal file
View File

@@ -0,0 +1,31 @@
function Get-UnifiConfigPath {
$dir = Join-Path $env:APPDATA 'UnifiCLI'
if (-not (Test-Path $dir)) {
New-Item -ItemType Directory -Path $dir -Force | Out-Null
}
Join-Path $dir 'config.json'
}
function Read-UnifiConfig {
$path = Get-UnifiConfigPath
if (Test-Path $path) {
Get-Content $path -Raw | ConvertFrom-Json -AsHashtable
} else {
$null
}
}
# Password is intentionally excluded — never written to disk
function Write-UnifiConfig {
param(
[Parameter(Mandatory)]
[hashtable]$Config
)
$safe = @{
ControllerUrl = $Config.ControllerUrl
Username = $Config.Username
DefaultSite = $Config.DefaultSite
SkipCertificateCheck = $Config.SkipCertificateCheck
}
$safe | ConvertTo-Json | Set-Content -Path (Get-UnifiConfigPath) -Encoding UTF8
}