Getting PowerShell to work with Home Assistant

I wanted to turn on and off my office lamp from my desktop, sure I can use a switch but it is hooked up to Home Assistant so lets make it automatic! The main scenario was to toggle it at 10pm so when I get distracted it will let me know the time. You can use this for just about anything and at some point I will add more functions. Here is the snippet for now. You can set the values of global in your profile or in the launching script. As long as they are set this will work.

Script

Just past this into a file and run after updating the password, URL for your Home Assistant installation and then the entity id.


function Set-HomeAssistantAccess($AccessKey, $BaseUrl) { $Global:HomeAssistantAccessKey = $AccessKey $Global:HomeAssistantBaseUrl = $BaseUrl $Global:HomeAssistantHeader = @{ "x-ha-access" = $AccessKey; "Content-Type" = "application/json"} } function Set-HomeAssistantSwitchState { param ( [String] $Entity, [ValidateNotNullOrEmpty()] [ValidateSet('On', 'Off')] [String] $State ) $body = @{entity_id = $Entity} | ConvertTo-Json switch ($State) { "On" { Invoke-RestMethod -Method POST -Uri "$Global:HomeAssistantBaseUrl/services/switch/turn_on" -Headers $Global:HomeAssistantHeader -Body $body } "Off" { Invoke-RestMethod -Method POST -Uri "$Global:HomeAssistantBaseUrl/services/switch/turn_off" -Headers $Global:HomeAssistantHeader -Body $body } Default {} } } Set-HomeAssistantAccess -AccessKey "youraccesskey" -BaseUrl "https://yourdomainorip/api" Set-HomeAssistantSwitchState -Entity "switch.yourlightentityid" -State On Set-HomeAssistantSwitchState -Entity "switch.yourlightentityid" -State Off

Home Assistant Links

Home Assistant

Sytone

I’m a principal engineer working at Microsoft. I have run and supported services for over twenty years and worked in multiple countries. I love working with passionate people and new technology.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.