Unifi.SwitchPoEPort.psm1
Function Connect-UnifiController{ # Import Credentials $ucXML = "$($env:PSModulePath.split(';') | Select-Object -First 1)\uc.xml" if(Test-Path $ucXML){ $credentials = Import-Clixml -Path $ucXML } else{ $credentials = Get-Credential -Message 'Enter Unifi Controller credentials' $credentials | Export-Clixml -Path $ucXML } # Import Unifi URL $baseURIxml = "$($env:PSModulePath.split(';') | Select-Object -First 1)\Unifi-URL.xml" if($env:UnifiURI){ # Variable already exists } elseif(Test-Path $baseURIxml){ $env:UnifiURI = Import-Clixml $baseURIxml } else{ $uri = Read-Host -Prompt "Please enter the Unifi URL (example: https://unifi.myserver.local:8443)" "$uri/api" | Export-Clixml $baseURIxml $env:UnifiURI = "$uri/api" } $loginURI = "$env:UnifiURI/login" [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} $AllProtocols = [System.Net.SecurityProtocolType]'Tls,Tls11,Tls12' [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols # Create JSON body $cred = "`{`"username`":`"$($credentials.UserName)`",`"password`":`"$($credentials.GetNetworkCredential().Password)`"`}" # Get Cookie Invoke-RestMethod -uri $loginURI -Method Post -Body $cred -ContentType "application/json" -SessionVariable Global:session | out-null # Cleanup credentials Remove-Variable credentials Remove-Variable cred } Function Set-UnifiPoEPort { Param( [Parameter(Mandatory)] $port, [ValidateSet("off", "auto")] $poe_mode = 'auto', $switchMAC = $(Get-UnifiSwitchID) ) # Connect to Unifi Controller Connect-UnifiController # Retreive current config [array]$data = (Invoke-RestMethod -Uri "$env:UnifiURI/s/default/stat/device/$switchMAC" -Method Post -Body "" -WebSession $Global:session).Data [array]$currentPO = $data.port_overrides if($currentPO.port_idx -contains $port){ # Port is already set in config, change current value $currentPO | Where-Object port_idx -eq $port | ForEach-Object { $_.poe_mode = $poe_mode } } else{ # Port is not yet listed, add it to the config $currentPO += [PSCustomObject]@{ port_idx = $port poe_mode = $poe_mode } } # Prepare body $body = [PSCustomObject]@{ port_overrides = $currentPO } | ConvertTo-Json -Depth 4 # Send new config Invoke-RestMethod -Uri "$env:UnifiURI/s/default/rest/device/$($data.device_id)" -Method Put -Body $body -ContentType "application/json" -WebSession $Global:session -UseBasicParsing } Function Get-UnifiSwitchID{ # Connecto to Unifi Controller Connect-UnifiController # Get Unifi Switch(es) and select the first object return ((Invoke-RestMethod -Uri "$env:UnifiURI/s/default/stat/device/" -Method Post -Body "" -WebSession $Global:session).Data | Where-Object type -eq 'usw' | Select-Object -First 1).mac } Export-ModuleMember -Function Connect-UnifiController Export-ModuleMember -Function Set-UnifiPoEPort Export-ModuleMember -Function Get-UnifiSwitchID |